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
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Haris
  • 191
  • 1
  • 4
  • 9
  • 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"`. ` – Valentin Bajrami Dec 05 '16 at 14:12

4 Answers4

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.

Fedor Dikarev
  • 1,761
  • 8
  • 13
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

debal
  • 3,664
  • 5
  • 17
  • 18
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

Wissam Roujoulah
  • 3,204
  • 1
  • 12
  • 21
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).

Petr Skocik
  • 28,176
  • 14
  • 81
  • 141