Bash unary operator expected
Solved
Hello,
I am a beginner in bash and I am trying to create a very simple script that only stops when the user says yes.
It gives me the error:
I know it's probably simple, but I searched and couldn't find it. If anyone could explain it to me, thank you.
I am a beginner in bash and I am trying to create a very simple script that only stops when the user says yes.
#!/bin/bash until [ "$var" = 'oui' ] do read -p 'say yes: ' var done
It gives me the error:
line 3: [: =: unary operator expected.
I know it's probably simple, but I searched and couldn't find it. If anyone could explain it to me, thank you.
1 answer
-
Hello
Problem Explanation
In your example,var
is not initialized,$var
is substituted with "nothing", resulting in the test:
until [ = 'yes' ] do ... done
Hence the error:=
is a binary operator (a left operand, a right operand) and consequently bash tells you that it might take a unary operator (like!
)... but not binary.
How to solve your problem
You need to:
- either test in advance ifvar
is a non-empty string (using-z
)
- or (which I recommend) put$var
in quotes every time you evaluate it in a test.
Personally, I advocate the second solution. Generally, a string in bash can contain spaces, and you'll run into the same kind of problem if you don't take this precaution.
#!/bin/bash until [ "$var" = 'yes' ] do read -p 'say yes: ' var done exit 0
Test:
(mando@aldur) (~) $ sh toto.sh
say yes:
say yes: no
say yes: yes yes
say yes: yes
Good luck