1

I have a shell script file, I check the $? is 0 to judge the script run successfully.

When the script has a error command, it will run failed, I think it will exit by 127, but if I use bash -l it still return 0, this make me dont know there is running successfully or command not found. BUt if no -l it return 127

there is my demo:

[root@T /tmp]# cat _script.sh
no_such_cmd
[root@T /tmp]# bash _script.sh
_script.sh: line 1: no_such_cmd: command not found
[root@T /tmp]# echo $?
127
[root@T /tmp]# bash -l _script.sh
no_such_cmd : command not found
[root@T /tmp]# echo $?
0
[root@T /tmp]# no_such_cmd
no_such_cmd : command not found
[root@T /tmp]# echo $?
0
[root@T /tmp]# zsh
[root@T]/tmp# no_such_cmd
zsh: command not found: no_such_cmd
[root@T]/tmp# echo $?
127
axiaoxin
  • 308
  • 6
  • 22
  • Cannot reproduce; I get the exact same error message and exit status for both `bash _scrip.sh` and `bash -l _script.sh`. – chepner Apr 12 '17 at 12:54
  • I suspect your shell init file (~/.bash_login, ~/.bash_profile, or ~/.profile) sets up something that runs automatically between interactive commands (e.g. a debug trap, PROMPT_COMMAND, or something similar), and the exit status from that is replacing that from the failed command. Try adding `set -x` to the script, and see what that shows. – Gordon Davisson Apr 12 '17 at 15:20
  • @GordonDavisson [root@T /tmp]# set -x _script.sh +++ history 1 +++ read x y +++ echo 2017-04-13 10:14:15 set -x _script.sh ++ z='2017-04-13 10:14:15 set -x _script.sh' +++ date +%c ++ echo -n '[' Thu Apr 13 10:14:15 2017 ']' +++ who am i ++ echo -n '[' root pts/4 Apr 12 18:59 '(10.123.138.138)' ']' ++ echo '[' 2017-04-13 10:14:15 set -x _script.sh ']' – axiaoxin Apr 13 '17 at 02:15

3 Answers3

1

I read the answer of @chepner in detecting command not found in bash script

and add the unset command_not_found_handle at the first line has solved the matter

Community
  • 1
  • 1
axiaoxin
  • 308
  • 6
  • 22
0

A snippet of code would help with a diagnosis. I'm running a very old version of bash (3.2.25) and I can't duplicate your results.

$ a
-bash: a: command not found
$ echo $?
127
$ bash --version
GNU bash, version 3.2.25(1)-release (i386-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.

But as previously stated, check if the command exists first. command -v might be what you're after.

Kind Stranger
  • 1,736
  • 13
  • 18
  • I checked agian, the bash version Has nothing to do with this matter,all of the error cmd on my machine exit by 0 – axiaoxin Apr 12 '17 at 12:50
-2

Maybe you can check the command exists before trying to call it: Check if a program exists from a Bash script

Community
  • 1
  • 1
Ville Oikarinen
  • 400
  • 1
  • 11