简体   繁体   English

bash 中的 if 子句中的读取命令

[英]Read command in if clause in bash

elif [ "$arg" == "--file" ]  || [ "$arg" == "-f" ] && [[ read var ]]
    then 
        touch $var

I'm writing a bash script which takes in a command-line input, either long-form or short-form along with the file name to create an empty file with touch command.我正在编写一个 bash 脚本,该脚本接受长格式或短格式的命令行输入以及文件名,以使用触摸命令创建一个空文件。 the above snippet is what I tried to do, but there's an error unary "read: unary operator expected".please help上面的代码片段是我试图做的,但是有一个错误 unary "read: unary operator expected".please help

This happens for most commands:大多数命令都会发生这种情况:

$ [[ echo "hello world" ]]
bash: conditional binary operator expected
bash: syntax error near `world"'

This is because [[.. ]] should be used to compare values, and not to run commands.这是因为[[.. ]]应该用于比较值,而不是运行命令。 To run a command, don't wrap it in anything:要运行命令,请不要将其包装在任何内容中:

$ echo "hello world"
hello world

Applied to your example:应用于您的示例:

echo "You are expected to type in a value, but you will receive no prompt."
arg="-f"
if [ "$arg" == "--file" ]  || [ "$arg" == "-f" ] && read var
then
  echo "You entered: $var"
fi

Bash needs to know that it's running a whole command Bash 需要知道它正在运行一个完整的命令

To make bash aware that it's running a command you can use the backtick syntax (not recommended) or the preferred $() command substitution syntax.要让 bash 知道它正在运行命令,您可以使用反引号语法(不推荐)或首选的$()命令替换语法。 Without this syntax, bash is assuming that you're putting two separate strings inside of that condition.如果没有这种语法,bash 会假设您在该条件中放置了两个单独的字符串。

The error you're getting is saying that you are trying to compare two strings without an operator to do so (ie -eq or == ).您得到的错误是说您正在尝试在没有运算符的情况下比较两个字符串(即-eq== )。

Here is an example of how to make it recognize your commands:以下是如何使其识别您的命令的示例:

elif [[ ... ]] && [[ $(read var) ]]
then

However, this won't work.但是,这行不通。 This will evaluate to false .这将评估为false This is because you haven't printed anything out and as such an empty string ( "" ) is falsey.这是因为您没有打印任何内容,因此空字符串 ( "" ) 是错误的。

echo your variable to test its value echo您的变量以测试其值

elif [[ ... ]] && [[ $(read var; echo $var) ]]
then

This will read into the variable and then test if the user has typed anything into it.这将读入变量,然后测试用户是否在其中输入了任何内容。 If the user doesn't type anything, it will evaluate to false , otherwise, it will evaluate to true and run the body of the elif statement.如果用户没有输入任何内容,它将评估为false ,否则,它将评估为true并运行elif语句的主体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM