bash 如果命令带有用户输入 OS X 终端

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18928260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:38:38  来源:igfitidea点击:

If command with user input OS X terminal

macosbashif-statementterminal

提问by Pistachios

So I'm new to the OS X terminal and I'm trying to figure out how to use the ifcommand with the readcommand.

所以我是 OS X 终端的新手,我正在尝试弄清楚如何将if命令与命令一起使用read

Like this:

像这样:

echo stuff:
read f
if [ "$f" == "y"]
then 
echo wassup
else exit

What am I doing wrong?

我究竟做错了什么?

回答by icktoofay

You're asking bash to compare whether the strings fand yare equivalent. Clearly, they're not. You need to use a variable substitution:

您要求 bash 比较字符串fy是否相等。显然,他们不是。您需要使用变量替换:

if [ "$f" == "y" ]

With this, it's asking “is the string consisting of the contents of the variable fequivalent to the string y?”, which is probably what you were trying to do.

有了这个,它会问“由变量的内容组成的字符串是否与字符串f等效y?”,这可能是您想要做的。

You're also missing an fi(ifbackwards), which ends the ifstatement. Together:

您还缺少一个fi(if向后),它结束了if语句。一起:

if [ "$f" == "y" ]
then
    # true branch
else
    # false branch
fi