I have two variables
var="" var1=abcd
Here is my shell script code
if [ $var == $var1 ]; then do something else do something fi
If I run this code it will prompt a warning
[: ==: unary operator expected
How can I solve this?
The word unary is basically synonymous with “single.” In the context of mathematics, this could be a single number or other component of an equation. So, when Bash says that it is expecting a unary operator, it is just saying that you are missing a number in the script.
$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.
Inside the function, $1 expands to the first positional parameter that was passed to the shell function, rather than to the script it's part of. Thus, like $# , the special parameters $1 , $2 , etc., as well as $@ and $* , also pertain to the arguments passed to a function, when they are expanded in the function.
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With