How to compare 2 lines in a shell?

I want the user to enter something on the command line with either -l or -e. so for example $. / report.sh -e I want the if statement to share any decision they made, so I tried ...

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

obviously not working thanks

+3
source share
4 answers

I use:

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

However, to analyze arguments getoptscan make your life easier:

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

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

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

, . , =. then.

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

, -e, , echo, - . echo -e, , echo -d echo -f , . -e echo.

+1

If you want to print only the parameter that the user sent, you can simply use echo "$1". If you want to return to the default value, if the user did not send anything, you can use echo "${1:--l}( :-- Bash syntax for the default values). However, if you need a really powerful and flexible argument handling, you can look at 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
+1
source

Source: https://habr.com/ru/post/1746719/


All Articles