I&QUOT如何;尝试做一些事情,然后检测是否失败"在bash? [英] How can I "try to do something and then detect if it fails" in bash?

查看:113
本文介绍了I&QUOT如何;尝试做一些事情,然后检测是否失败"在bash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在回答一个previous问题:

<一个href=\"http://stackoverflow.com/questions/7251335/how-can-i-use-do-i-have-root-access-as-a-conditional-in-bash/7251384#7251384\">How我可以用'我有root权限?如在bash条件?

的建议,尽量做一些事情,发现如果失败',而不是'检查权限,然后做一些事情

我已经找到了很多理由为这个例如:

关于

不过,我发现很少明确的信息如何在bash实施的try / catch。我猜想,这是太容易了,只是在使用函数或其他脚本什么我发现似乎相当complicated-:

我是比较新的,但来砸困惑,有没有类似尝试在其他语言功能。

一个简单的函数

具体而言,我想做到以下几点:

  CMD =`/路径/要/ script.sh`
如果[&LT;回声$ CMD | grep的错误是真&gt; ];然后
        .. 做这个 ..
其他
        .. 去做 ..
科幻


解决方案

 如果sudo的文件模式A-X / etc / shadow中2  - ;的/ dev / null的
那么:是的 - 我有root权限
其他:不 - 我没有root权限或/ etc / shadow文件不存在或...
科幻

这个选择,做任何损害,如果它成功(影子密码文件不应该执行的操作,你可以不喜欢 CHMOD流/ - 除去公共写信如果preFER根目录权限),并检查它的工作通过查看命令的退出状态。该扔掉的错误信息 - 你必须决定是否该事项

在'须藤'是有提高的特权;如果你认为用户应该已经是根,那么省略'须藤'。

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   

解决方案

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

这篇关于I&QUOT如何;尝试做一些事情,然后检测是否失败&QUOT;在bash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆