开发者

bash: Can't get simple 'if' to work

开发者 https://www.devze.com 2023-03-02 14:11 出处:网络
I don\'t understand why this simple read doesn\'t work. Mind you, I am VERY new to bash. :) #!/bin/bash

I don't understand why this simple read doesn't work. Mind you, I am VERY new to bash. :)

#!/bin/bash

echo -n "Project Name: " 
read PROJECT_NAME

if [ -n "$PROJECT_NAME" ]; then
    echo "You must provide a project name."
    exit 2
fi

-- snip --

When this executes, it asks for the project name. After I press enter, I get 开发者_如何转开发"You must provide a project name." and then the scripts exists instead of continuing.

What am I doing wrong?

Thanks Eric


You want [ -z "$PROJECT_NAME" ], not -n:

From man test:

   -n STRING
          the length of STRING is nonzero

...

   -z STRING
          the length of STRING is zero


to avoid confusion from -n or -z , you can just use case/esac to compare strings

case "$PROJECT_NAME" in
"" ) echo "No";;
*) echo "Have";;
esac
0

精彩评论

暂无评论...
验证码 换一张
取 消