3

Try to test command exist or not using simple script

$ cat test.sh
command -v nwef
echo $?

$ sh test.sh
127
$ ./test.sh
1
$ bash test.sh
1

In centos 6.5, the result is always 1.

Anyone know why "sh test.sh" is different?

1
  • Check what is sh. I guess debian-derived systems have a strange beast like /bin/ash or /bin/sash as a "basic shell". If it is, then your should check the command behaviour, I don't know what it does Feb 8, 2014 at 5:46

2 Answers 2

3

sh in Ubuntu is dash, not bash.

2

The differences in exit statuses are with your usage of the command builtin and how Bash and Dash treat them differently.

In man bash:

  command [-pVv] command [arg ...]

... If the -V or -v option is supplied, the exit status is 0 if command was found, and 1 if not. If neither option is supplied and an error occurred or command cannot be found, the exit status is 127. Otherwise, the exit status of the command builtin is the exit status of command.

This is why you get an exit 1 with Bash.

Since Dash does not treat -v option in command as Bash does, it treats nwef as "command not found", which is exit 127.

I think it's also important to note here how Debian treats ./test.sh differently than sh test.sh. Since the script does not contain a shebang path to an interpreter like #!/bin/sh, running ./test.sh defaults to #!/bin/bash instead of #!/bin/sh and treats your usage of command with exit 1. Unfortunately, I cannot find an explanation for this in documentation.

1
  • The command builtin is also included in Dash, I think it just doesn't treat the -v option as Bash does. Post updated.
    – John B
    Feb 9, 2014 at 0:51

Your Answer

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

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