简体   繁体   中英

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. the above snippet is what I tried to do, but there's an error 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

To make bash aware that it's running a command you can use the backtick syntax (not recommended) or the preferred $() command substitution syntax. Without this syntax, bash is assuming that you're putting two separate strings inside of that condition.

The error you're getting is saying that you are trying to compare two strings without an operator to do so (ie -eq or == ).

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 . This is because you haven't printed anything out and as such an empty string ( "" ) is falsey.

echo your variable to test its value

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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