Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 768
linbo Avatar asked Jul 15 '26 14:07

linbo


2 Answers

sh in Ubuntu is dash, not bash.

like image 199
Ignacio Vazquez-Abrams Avatar answered Jul 17 '26 16:07

Ignacio Vazquez-Abrams


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.

like image 31
John B Avatar answered Jul 17 '26 15:07

John B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!