[: =: unary operator expected



  • Hi, I am getting this error when running my script.

    $ ./forloop.sh
    ./forloop.sh: line 10: [: =: unary operator expected
    
    #!/bin/bash 
    for i in *
    do 
    [ -d "$i" ] || continue
    Dirname="$i"
    echo $Dirname is a directory
    [ $i = rootfs ] && break
    done 
    
    if [ $Dirname = rootfs ];then
    echo "Cannot continue processing rootfs found"
    fi
    


  • @vaquitasos you are getting this because the last check you are doing

    if [ $Dirname = rootfs ];then
    echo "Cannot continue processing rootfs found"
    fi
    

    The $Dirname is empty, running your script through debug will show something like: + '[' = rootfs ']', it is because of this bash is giving you the error.

    Try your script like this:

    #!/bin/bash 
    for Dirname in *
    do 
    [ -d "$Dirname" ] || continue
    echo "$Dirname" is a directory
    [ "$Dirname" = rootfs ] && break
    done 
    
    if [ "$Dirname" = rootfs ];then
    echo "Cannot continue processing rootfs found"
    fi
    

    Make your for loop variable, the actual variable you are going to use, instead of reassigning $i to $Dirname, put double quotes around $Dirname. You have to be careful when using single square brackets and double quotes.



  • @petulia3478 Hey there! thanks for the tips on this, really useful.


Log in to reply
 

© Lightnetics 2024