Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

if statement - How can I "try to do something and then detect if it fails" in bash?

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   
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...