0

here is my shell script, I tried to catch the failing command and print the its result:

myfunc() {
  $1
  uptime

  echo "-------------------------------------"
  
  EXIT_STATUS=$?
  if [ ! "$EXIT_STATUS" = "0" ]; then
    echo "Exit on failure"
  else
    echo "Exit on success"
  fi
}

myfunc pwd
myfunc failfail

which results in:

/root
 15:19:54 up 15:43,  3 users,  load average: 0.01, 0.09, 0.09
-------------------------------------
Exit on success
test2.sh: line 4: failfail: command not found
 15:19:54 up 15:43,  3 users,  load average: 0.01, 0.09, 0.09
-------------------------------------
Exit on success

which second time should print Exit on failure, I tried with set -e but actually it exit the code and not continue to if else statement.

MK83
  • 616
  • 6
  • 8
  • ...if your _real_ goal is to find any unchecked command with status 0, that's what an ERR trap is for. – Charles Duffy Nov 04 '20 at 15:59
  • BTW, note that you should probably be running `local exit_status; "$@"; exit_status=$?` at the top of `myfunc`. The `echo` needs to be _after_ you collected `$?`, and if you don't declare `exit_status` local, the assignment is going to change it globally for your script. – Charles Duffy Nov 04 '20 at 16:02
  • (Use of lower-case variables above is also intentional; see the relevant section of the POSIX standard at https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html specifying that all variable names that modify behavior of the shell or other POSIX-specified utilities shall be all-caps, whereas variable names with at least one lower-case character are reserved for applications to use; read that keeping in mind that environment variables and regular shell variables share a single namespace, so the conventions apply to both). – Charles Duffy Nov 04 '20 at 16:03

1 Answers1

0

I think the problem is that the if checks for the last run command which is the echo command and therefore it is always 0

to solve this simply move your EXIT_STATUS=$? line directly under the $1 line

pt1997
  • 29
  • 3
  • Echo does not matter here, you can remove it. the issue is I want to catch the command which fails no matter of the order. If I remove echo still I will get success as `uptime` is always return 0. your idea is more a hack rather than solution although it fix this example but not resolving if I have lots of command and I want to find the failing cmd. – MK83 Nov 04 '20 at 14:38
  • then you would need to add a check after every command that updates the var only if its 1 – pt1997 Nov 04 '20 at 14:40
  • that's I did and do not like but it seems the only option. – MK83 Nov 04 '20 at 14:45
  • 1
    @MK83, `somecommand || (( exit_status |= $? ))` is your friend, if you want to build up a composite exit status (ORing in each other command's return value into what you eventually return yourself). – Charles Duffy Nov 04 '20 at 15:58