Bash unary operator expected

Solved
bash -  
mamiemando Posted messages 33228 Registration date   Status Moderator Last intervention   -
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.

#!/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

  1. mamiemando Posted messages 33228 Registration date   Status Moderator Last intervention   7 944
     
    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 if
    var
    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
    7
    1. bash
       
      Thank you very much for taking the time to reply to me, mamiemando. My script works and I understand now, thank you!!
      1
    2. mamiemando Posted messages 33228 Registration date   Status Moderator Last intervention   7 944
       
      You're welcome :-) Have a great day!
      1