Difference between revisions of "What does "unary operator expected" mean"
From Linuxintro
imported>ThorstenStaerk |
imported>ThorstenStaerk |
||
Line 8: | Line 8: | ||
EOF | EOF | ||
[[chmod]] 777 test.sh | [[chmod]] 777 test.sh | ||
− | After you did this, you have a script test.sh that will ask you for your name and say "I know you" if your name is Thorsten. | + | After you did this, you have a script test.sh that will ask you for your name and say "I know you" if your name is Thorsten. You can call the script using the [[command]] |
+ | ./test | ||
Now if you don't enter a name and just press enter you will get this: | Now if you don't enter a name and just press enter you will get this: | ||
+ | # ./test.sh | ||
+ | how is your name? | ||
+ | |||
+ | ./test.sh: line 3: [: =: unary operator expected | ||
+ | This is clearly a problem in line 3. $name is replaced by ''nothing'' when the shell executes the line. So the remainder of the line reads | ||
+ | if [ = "Thorsten" ]; then echo "I know you"; fi | ||
+ | Which does not work because you cannot compare ''nothing'' with "Thorsten". |
Revision as of 14:28, 20 December 2011
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 example, let's write a short bash script. Just copy and paste the lines below into a Linux Shell:
cat >test.sh<<EOF echo "how is your name? " read name if [ $name = "Thorsten" ]; then echo "I know you"; fi EOF chmod 777 test.sh
After you did this, you have a script test.sh that will ask you for your name and say "I know you" if your name is Thorsten. You can call the script using the command
./test
Now if you don't enter a name and just press enter you will get this:
# ./test.sh how is your name? ./test.sh: line 3: [: =: unary operator expected
This is clearly a problem in line 3. $name is replaced by nothing when the shell executes the line. So the remainder of the line reads
if [ = "Thorsten" ]; then echo "I know you"; fi
Which does not work because you cannot compare nothing with "Thorsten".