1

I need to check the command executed is success or not, I have place the below code in test.sh run it, which give the out by listing the content of /home but there is a warning

./test.sh: 3: ./test.sh: [[: not found

What's wrong in below command

#!/bin/sh
ls /home/
if [[ "$?" != 0 ]]; then
echo "Commnad Error"
else
echo "Commnad Success"
fi
1
  • There is no need to check the status of the previous command. You can and should do something liike ls /home 2>/dev/null || echo "Command Error". ` Dec 5 '16 at 14:12
3

According to error:

./test.sh: 3: ./test.sh: [[: not found

Your /bin/sh isn't bash and [[ is bash-specific. Use single bracket [ or test command by itself.
And also use -ne for numeric conditionals. != will work in your specific case, but it's bad practice.

2

The error is at if [[ "$?" != 0 ]]; then

number comparison is not done using != Instead -ne is supposed to be used.

Read here for numeric comparison

Also, the correct sytax for the status of the last executed command exit code is $? without the quotes.

if [[ $? -ne 0 ]]; then

2
  • Thanks, the problem was with syntax error also there was no need of [ twice, I changed the code to ` if [ $? -ne 0 ]; then` and working.
    – Haris
    Dec 5 '16 at 13:58
  • that doesn't work Dec 5 '16 at 13:58
1

I guess you are using dash to execute the script because the /bin/sh is a link so you can instead using bash like #!/bin/bash then that warning

0

Dash doesn't have [[, only [. But even with [, there are reasons to prefer if your_command over your_command; if [ $? = 0 ]. (The former is more straightforward, faster, and resilient to failures in set -e mode).

Not the answer you're looking for? Browse other questions tagged or ask your own question.