Comparing two strings in Bash

114,994

Solution 1

The right way to compare those two strings (S1 and S2) using if is:

if [ "$S1" = "$S2" ]

Do not be stingy in use spaces in this case.

See: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

Solution 2

In bash scripting you need to compare two variable with below method.

if [ "var1" != "var2" ]; then
  Do something
fi;

Spaces are important

Solution 3

You may also use GNU test, for example:

test s1 = s2 && echo Equal || echo Not equal

In your context, it is:

test "$S1" = "$S2" && rmdir -v /home/william/test
Share:
114,994

Related videos on Youtube

Desert_foxhole
Author by

Desert_foxhole

Updated on September 18, 2022

Comments

  • Desert_foxhole
    Desert_foxhole over 1 year

    I would like to make a script that deletes a directory with rmdir after confirming with a password using read to set the variable.

    So far I have this:

    #!/bin/bash -x
    echo "Password:"
    read -t 30 S1
        S2='55555'
    if [ $S1=$S2 ]; then
        rmdir /home/william/test
    else
        echo "fail"
    sleep 10
    fi
    

    So, I have the -x to try to debug it but every time the script either fails to echo (if I put the password in wrong) or it wont remove the directory needed.

    If someone has a modifiable script that I could use or if you could point out the problems with the current script that would be great.

  • codeforester
    codeforester about 6 years
    TLDP is not an authentic site as it has a lot of inconsistencies and errors. I would advise that we don't use it as a reference.