linbo
linbo

Reputation: 2431

execute shell script directly differ from using sh command in ubuntu 12.04

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?

Upvotes: 3

Views: 1814

Answers (2)

John B
John B

Reputation: 3646

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.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

sh in Ubuntu is dash, not bash.

Upvotes: 3

Related Questions