开发者

Why is the value of this string, in a bash script, being executing?

Why is this script executing the string in the if statement:

#!/bin/bash
FILES="*"
STRING=''

for f in $FILES
do
  if ["$STRING" = ""]
   then
    echo first
    STRING='he开发者_高级运维llo'
   else
    STRING="$STRING hello"
  fi
done

echo $STRING

when run it with sh script.sh outputs:

first
lesscd.sh: line 7: [hello: command not found
lesscd.sh: line 7: [hello hello: command not found
lesscd.sh: line 7: [hello hello hello: command not found
lesscd.sh: line 7: [hello hello hello hello: command not found
lesscd.sh: line 7: [hello hello hello hello hello: command not found
hello hello hello hello hello hello

p.s. first attempt at a shell script

thanks


You are trying to execute the command [hello. Put a space after [ so it will be regognized as a test.

for f in $FILES
do
  if [ "$STRING" = "" ]
   then
    echo first
    STRING='hello'
   else
    STRING="$STRING hello"
  fi
done


Assuming that the line 'echo first' is merely for debugging, you can achieve the same thing with:

STRING=$STRING${STRING:+ }hello

(That is, the above line will produce the same result as your if statement, but will not echo 'first')

The expression '${STRING:+ }' evaluates to nothing if $STRING is empty or null, and it evaluates to a space otherwise.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜