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

From Linuxintro
imported>ThorstenStaerk
(Created page with "When you work with Linux scripts on the command line, you will sometimes get an error message saying unary operator expected And you may wonder what this means. To give you an e...")
 
 
(16 intermediate revisions by one other user not shown)
Line 1: Line 1:
When you work with Linux scripts on the command line, you will sometimes get an error message saying
+
The bash message
 
  unary operator expected
 
  unary operator expected
And you may wonder what this means. To give you an example, let's write a short bash script. Just copy and paste the lines below into a Linux Shell:
+
means that you do a comparison where one site is empty for example
  [[cat]] >test.sh<<EOF
+
if [ $name = "foo" ]
[[echo]] "how is your name? "
+
and $name is empty. Then the bash shell internally replaces $name by an empty string and it will be interpreted as
[[read]] name
+
if [ = "foo" ]
[[if]] [ $name = "thorsten" ]; then echo "I know you"; fi
+
and this is not a valid expression.
EOF
+
 
[[chmod]] 777 test.sh
+
The solution is to quote variable names like this:
After you did this, you have a script test.sh
+
  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:
 +
<pre>
 +
tweedleburg:~ # bash -x test.sh  
 +
+ echo 'how is your name? '
 +
how is your name?  
 +
+ read name
 +
 
 +
+ '[' = foo ']'
 +
test.sh: line 3: [: =: unary operator expected
 +
</pre>
 +
 
 +
= See also =
 +
* [[troubleshooting]]
 +
* [[error messages]]
 +
* [[shell scripting tutorial]]

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