我如何使用文件的grep比较一个bash if / else语句里面呢? [英] How do I use a file grep comparison inside a bash if/else statement?
问题描述
在我们的服务器出现时,我们需要检查文件查看服务器的配置方式。
我们希望搜索我们的/etc/aws/hosts.conf文件中的以下字符串:
MYSQL_ROLE =主
然后,我们要测试该字符串是否存在并使用if / else语句来运行取决于字符串是否存在与否两个选项之一。
什么是if语句的语法BASH?
如果[????? ];然后
#do一件事
其他
#do另一件事
科幻
从的grep --help
,还能看到的男人的grep :
退出状态为0,如果是选择任何行,否则为1;
如果发生任何错误,并且没有给出-q,退出状态为2。
块引用>如果grep的--quiet MYSQL_ROLE =主/etc/aws/hosts.conf;然后
回声存在
其他
回声未找到
科幻您可能需要使用一个更具体的正则表达式,如
^ MYSQL_ROLE =主$
,以避免意见,这仅仅是与主开头命名的字符串,等等。这工作,因为的如果的接受命令并运行它,并使用该命令的返回值来决定如何进行,用0表示真实,不为零的含义假—以下同如何其他返回codeS是由shell PTED间$ p $,而像C语言的相反。
When our server comes up we need to check a file to see how the server is configured.
We want to search for the following string inside our /etc/aws/hosts.conf file:
MYSQL_ROLE=master
Then, we want to test whether that string exists and use an if/else statement to run one of two options depending on whether the string exists or not.
What is the BASH syntax for the if statement?
if [ ????? ]; then #do one thing else #do another thing fi
解决方案From
grep --help
, but also see man grep:Exit status is 0 if any line was selected, 1 otherwise; if any error occurs and -q was not given, the exit status is 2.
if grep --quiet MYSQL_ROLE=master /etc/aws/hosts.conf; then echo exists else echo not found fi
You may want to use a more specific regex, such as
^MYSQL_ROLE=master$
, to avoid that string in comments, names that merely start with "master", etc.This works because the if takes a command and runs it, and uses the return value of that command to decide how to proceed, with zero meaning true and non-zero meaning false—the same as how other return codes are interpreted by the shell, and the opposite of a language like C.
这篇关于我如何使用文件的grep比较一个bash if / else语句里面呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!