10

Could somebody explain what this bit of code means please ?

I believe the second line is "if the exit status is zero", then echo "valid command" but I dont understand the first line

$@ &>/dev/null
if [[ $? = 0 ]]
then
   echo "Valid command"
fi

3 Answers 3

7

The first line runs the command formed by simply using all arguments to the script, and redirecting the output to /dev/null which essentially throws it away.

The built-in variable $@ expands to all of the positional parameters, with each parameter is a quoted string, i.e. the parameters are passed on intact, without interpretation or expansion. To get this effect, I believe you need to quote the use of the variable, i.e. say "$@".

The operator &> redirects both stdout and stderr.

Sign up to request clarification or add additional context in comments.

3 Comments

Just to support: explanation is found here: tldp.org/LDP/abs/html/internalvariables.html#APPREF
I think that $* and $@ are only different when surrounded by double quotes.
@mkb: you are right. I fear @unwind is not: without specifing "$@", the parameters would get whitespace split, i.e. function TT () { $@ ; } ; TT ls 1 2 '3 4'
4

According to the manual, $@ expands to the positional parameters, starting from one. If you call this script as scripty.sh ls /, it will execute ls / while redirecting all output to the bit bucket. That should return success (I hope!) and thus the script will print Valid command. If you call it scripty.sh ls /some/nonexistent/directory then the ls command should fail, and the script will output nothing.

Actually, I think the script can be improved to putting double quotes around $@ so that arguments with spaces in them don't trip up the interpreter.

With $@ the command ls "/Library/Application Support" is expanded to three words. With "$@" it's expanded to two, and the command is run just as it would be without the script wrapping it.

Comments

2

I'd like to add that this is unnecessarily verbose and could be shortened to

if "$@" &>/dev/null
then
    echo "Valid command"
fi

or even shorter

"$@" &>/dev/null && echo "Valid command"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.