2

In this Bash Shell script I like to check if the length of the string is zero. In that case the script should echo an error message and exit.

dbname="ssss"
dbuser=""

if [ -z "$dbname"]
then
        echo "DB name is not specified!"
        exit
fi

if [ -z "$dbuser"]
then
        echo "DB user is not specified!"
        exit
fi

If dbname is "" it works as expected. But if it has some value and I was expecting to see it exit at the next conditional, I get this error message:

Script.sh: line 4: [: missing `]'
DB user is not specified!

Why the error message?

1
  • 3
    You are working too hard. Try ${dbname:?DB name is not specified} Commented Dec 27, 2011 at 21:29

2 Answers 2

5
[ -z "$dbuser"]

should be

[ -z "$dbuser" ]
# note: ------^
Sign up to request clarification or add additional context in comments.

Comments

1

You are missing a space after the quotes.

if [ -z "$dbuser"]

If $dbuser is empty, it looks like this to bash, which is valid because it has a space:

if [ -z ]

When $dbuser is populated, the ] will be attached to the string, and will think the ] is part of the string:

if [ -z theuser]

To fix this, just add a space after your second double quote:

if [ -z "$dbuser" ]

Now, it'll get translated as the following, and everything is fine:

if [ -z theuser ]

Comments

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.