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 réponse
Hello
Problem Explanation
In your example,
Hence the error:
How to solve your problem
You need to:
- either test in advance if
- or (which I recommend) put
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.
Test:
Good luck
Problem Explanation
In your example,
varis not initialized,
$varis 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 if
varis a non-empty string (using
-z)
- or (which I recommend) put
$varin 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
bash
Thank you very much for taking the time to reply to me, mamiemando. My script works and I understand now, thank you!!
mamiemando
Posted messages
33540
Registration date
Status
Modérateur
Last intervention
7 927
You're welcome :-) Have a great day!