Difference between revisions of "What does "unary operator expected" mean"

From Linuxintro
imported>ThorstenStaerk
 
(4 intermediate revisions by one other user not shown)
Line 1: Line 1:
<metadesc>Here is why you get the error message "unary operator expected" and how to resolve it.</metadesc>
+
The bash message
When you work with Linux scripts on the command line, you will sometimes get an error message saying
 
 
  unary operator expected
 
  unary operator expected
 
+
means that you do a comparison where one site is empty for example
This means that there is a comparison where one site is empty for example
+
  if [ $name = "foo" ]
  if [ $name = "Thorsten" ]
+
and $name is empty. Then the bash shell internally replaces $name by an empty string and it will be interpreted as
and $name is empty. Then the bash shell will replace $name by an empty string and it will be interpreted as
+
  if [ = "foo" ]
  if [ = "Thorsten" ]
 
 
and this is not a valid expression.
 
and this is not a valid expression.
  
The solution is to quote the variable names like this:
+
The solution is to quote variable names like this:
  if [ "$name" = "Thorsten" ]
+
  if [ "$name" = "foo" ]
 
Then it will work.
 
Then it will work.
  
 
= Shell scripting tutorial =
 
= Shell scripting tutorial =
Try the [[shell scripting tutorial]] to avoid this mistake and similar ones in the future.
+
Try the tutorial [[BaBE - Bash By Examples]] to avoid this and similar mistakes in the future.
  
 
= Debugging bash scripts =
 
= Debugging bash scripts =
Line 24: Line 22:
 
+ read name
 
+ read name
  
+ '[' = Thorsten ']'
+
+ '[' = foo ']'
 
test.sh: line 3: [: =: unary operator expected
 
test.sh: line 3: [: =: unary operator expected
 
</pre>
 
</pre>

Latest revision as of 19:15, 24 December 2014

The bash message

unary operator expected

means that you do a comparison where one site is empty for example

if [ $name = "foo" ]

and $name is empty. Then the bash shell internally replaces $name by an empty string and it will be interpreted as

if [ = "foo" ]

and this is not a valid expression.

The solution is to quote variable names like this:

if [ "$name" = "foo" ]

Then it will work.

Shell scripting tutorial

Try the tutorial BaBE - Bash By Examples to avoid this and similar mistakes in the future.

Debugging bash scripts

You can also debug the script line-by-line using bash -x. bash -x shows all commands that are being executed, just like gdb or strace, but for bash scripts:

tweedleburg:~ # bash -x test.sh 
+ echo 'how is your name? '
how is your name? 
+ read name

+ '[' = foo ']'
test.sh: line 3: [: =: unary operator expected

See also