Bash script – test not working as expected

Issue

here is my simple script prova.sh:

#!/bin/bash
echo "\$# = [$#]"

echo "\$1 = [$1]"

if [ $# -ge 2 || $1="-h" ]
then
echo "#########################################################################"
echo -e "usage: $0 \t launches the program only"
echo -e "       $0 -s\t shows the command fired and launches the program"
echo -e "       $0 -so\t shows only the command fired"
echo -e "       $0 -h\t shows this guide"
echo "#########################################################################"
exit 0
fi

command="ls -la"

if test "$1"="-so" || "$1"="-s"
then
        echo "Fired command:" 
        echo $command
fi


if test "$1"!="-so"
then
        $command
fi

here is the output:

$> ./prova.sh -h

$# = [1]

$1 = [-h]

./prova.sh: row 6 : [: "]" missing

./prova.sh: row6: -h=-h: command not found

Fired command:
ls -l

totale 4

-rwxrw-r--. 1 user user 632 20 lug 16.13 prova.sh

I expected just the help

Solution

you need to close every test using single brackets, the shell way, if [ $# -ge 2 ] || [ $1 = "-h" ]; then ... this will fix it. If you still use single brackets way, is safe to enclose you variables with double quotes, so if they are empty, you are safe, like this if [ "$#" -ge 2 ] || [ "$1" = "-h" ]; then ... or you can just put them inside a double bracket, and bash will handle this for you if [[ $# -ge 2 || $1 = "-h" ]]; then ...

Answered By – Kaneda

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published