How can I “try to do something and then detect if it fails” in bash?

前端 未结 3 1957
后悔当初
后悔当初 2020-12-19 14:21

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 de

3条回答
  •  醉话见心
    2020-12-19 15:06

    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'.

提交回复
热议问题