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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With