How do i compare 2 strings in shell?

22,111

Solution 1

I use:

if [[ "$1" == "-e" ]]; then
    echo "-e"
else
    echo "-l";
fi

However, for parsing arguments, getopts might make your life easier:

while getopts "el" OPTION
do
     case $OPTION in
         e)
             echo "-e"
             ;;
         l)
             echo "-l"
             ;;
     esac
done

Solution 2

If you want it all on one line (usually it makes it hard to read):

if [ "$1" = "-e" ]; then echo "-e"; else echo "-l"; fi

Solution 3

You need spaces between the square brackets and what goes inside them. Also, just use a single =. You also need a then.

if [ $1 = "-e" ]
then
   echo "-e"
else
   echo "-l"
fi

The problem specific to -e however is that it has a special meaning in echo, so you are unlikely to get anything back. If you try echo -e you'll see nothing print out, while echo -d and echo -f do what you would expect. Put a space next to it, or enclose it in brackets, or have some other way of making it not exactly -e when sending to echo.

Solution 4

If you just want to print which parameter the user has submitted, you can simply use echo "$1". If you want to fall back to a default value if the user hasn't submitted anything, you can use echo "${1:--l} (:- is the Bash syntax for default values). However, if you want really powerful and flexible argument handling, you could look into getopt:

params=$(getopt --options f:v --longoptions foo:,verbose --name "my_script.sh" -- "$@")

if [ $? -ne 0 ]
then
    echo "getopt failed"
    exit 1
fi

eval set -- "$params"

while true
do
    case $1 in
        -f|--foo)
            foobar="$2"
            shift 2
            ;;
        -v|--verbose)
            verbose='--verbose'
            shift
            ;;
        --)
            while [ -n "$3" ]
            do
                targets[${#targets[*]}]="$2"
                shift
            done
            source_dir=$(readlink -fn -- "$2")
            shift 2
            break
            ;;
        *)
            echo "Unhandled parameter $1"
            exit 1
            ;;
    esac
done

if [ $# -ne 0 ]
then
    error "Extraneous parameters." "$help_info" $EX_USAGE
fi
Share:
22,111
Thomas
Author by

Thomas

Updated on December 18, 2020

Comments

  • Thomas
    Thomas over 3 years

    I want the user to input something at the command line either -l or -e. so e.g. $./report.sh -e I want an if statement to split up whatever decision they make so i have tried...

    if [$1=="-e"]; echo "-e"; else; echo "-l"; fi
    

    obviously doesn't work though Thanks

  • SourceSeeker
    SourceSeeker almost 14 years
    You say "getopt" and "getopts". They're two different things. The former is a separate executable and the latter is a shell builtin.