Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain this bit of code

Tags:

bash

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
like image 829
frodo Avatar asked Dec 06 '11 15:12

frodo


2 Answers

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.

like image 177
unwind Avatar answered Oct 19 '22 12:10

unwind


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.

like image 34
Matt K Avatar answered Oct 19 '22 14:10

Matt K