4

In an answer to a previous question:

How can I use 'do I have root access?' as a conditional in bash?

The suggestion to 'try to do something and detect if it fails' instead of 'check permission and then do something'

I have found plenty of rationale for this e.g.:

However, I have found very little clear information about how to implementing try/catch in bash. I would guess that it is too easy, except that what I have found seems rather complicated- using functions or other scripts:

I am relatively new to bash but confused that there is not a simple function similar to the try function in other languages.

specifically, I would like to do the following:

CMD=`./path/to/script.sh`
if [ <echo $CMD | grep error is true> ]; then
        .. do this ..
else 
        .. do that ..
fi   
Community
  • 1
  • 1
David LeBauer
  • 28,793
  • 27
  • 106
  • 180

3 Answers3

6
if sudo chmod a-x /etc/shadow 2>/dev/null
then : Yes - I have root permissions
else : No - I do not have root permissions or /etc/shadow does not exist or ...
fi

This chooses an operation that does no damage if it succeeds (the shadow password file is not supposed to be executable; you could do something like chmod o-w / - remove public write permission from the root directory if you prefer), and check that it worked by looking at the exit status of the command. This throws away the error message - you have to decide whether that matters.

The 'sudo' is there to raise the privileges; if you think the user should already be 'root', then omit the 'sudo'.

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
1

Bash depends on exit status so there isn't any try/catch equivalent. But it's still powerful to fit your needs.

For simple cases, you can use

[[ your_test_expression ]] && commands

This is equivalent to

if [[ your_test_expression ]]; then
    commands
fi

If uses the "exit status" of [[ ... ]] so actually you can use any command after if. Just make sure your control logic depends on the exit status of the command.

For complicated cases, you still need if or case statements to express your logic.

Mu Qiao
  • 6,363
  • 28
  • 34
0

unless the script you are calling has an exit condition, there isn't much you can do. However look up "set" in the bash man page.

set -e

will cause a script to exit if a simple command in it fails. You can add it to the top of script.sh in your example to cause it to exit if it fails.

also look at trap. I believe

trap 'exit 2' ERR

is similar

user916499
  • 65
  • 1
  • 1
  • 7