3

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?

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

need a space before the closing ] too
With this script I get -bash: [: =: unary operator expected
yes, see in-line edit, added dbl-quotes around your first $1. Good luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.