Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble Passing Parameter into Simple ShellScript (command not found)

I am trying to write a simple shell-script that prints out the first parameter if there is one and prints "none" if it doesn't. The script is called test.sh

    if [$1 = ""]
    then
        echo "none"
    else
        echo $1
    fi

If I run the script without a parameter everything works. However if I run this command source test.sh -test, I get this error -bash: [test: command not found before the script continues on and correctly echos test. What am I doing wrong?

like image 206
Spencer Avatar asked Dec 20 '25 05:12

Spencer


1 Answers

you need spaces before/after '[',']' chars, i.e.

if [ "$1" = "" ] ; then
#---^---------^ here
   echo "none"
else
    echo "$1"
fi

And you need to wrap your reference (really all references) to $1 with quotes as edited above.

After you fix that, you may also need to give a relative path to your script, i.e.

source ./test.sh -test
#------^^--- there

When you get a shell error message has you have here, it almost always helps to turn on shell debugging with set -vx before the lines that are causing your trouble, OR very near the top your script. Then you can see each line/block of code that is being executed, AND the value of the variables that the shell is using.

I hope this helps.

like image 150
shellter Avatar answered Dec 22 '25 19:12

shellter