Thomas
Thomas

Reputation: 31

How do i compare 2 strings in shell?

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

Upvotes: 3

Views: 22827

Answers (4)

l0b0
l0b0

Reputation: 58788

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

Upvotes: 1

David Wolever
David Wolever

Reputation: 154474

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

Upvotes: 10

Phil
Phil

Reputation: 2917

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.

Upvotes: 1

Dennis Williamson
Dennis Williamson

Reputation: 360005

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

Upvotes: 3

Related Questions