1

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

DDS
  • 2,340
  • 16
  • 34
  • Consider making a habit of using http://shellcheck.net/ before asking questions here. – Charles Duffy Jul 20 '22 at 16:42
  • BTW, running `$command` is inherently buggy; see [BashFAQ #50](https://mywiki.wooledge.org/BashFAQ/050), *I'm trying to put a command in a variable, but the complex cases always fail!* – Charles Duffy Jul 20 '22 at 19:26

1 Answers1

1

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 ...

Kaneda
  • 722
  • 5
  • 16
  • 1
    `[ "$1"="-h" ]` is still wrong -- needs to be `[ "$1" = "-h" ]` _with the spaces_ to not be always true. – Charles Duffy Jul 20 '22 at 16:43
  • of course, sorry, I forgot that whitout spaces is just an assignment – Kaneda Jul 20 '22 at 19:20
  • 1
    inside `[`, it's not even an assignment, it's a test for whether the string `"${1}-h"` is empty (identical to `[ -n "${1}-h" ]`), and it's _always_ nonempty because it always contains the text `-h`, hence always true. – Charles Duffy Jul 20 '22 at 19:25