Monday, February 21, 2011

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

Hello

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='hello'
   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

From stackoverflow
  • 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
    
    Ross : thanks. i'm going to learn ruby instead : )
  • 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 comments:

Post a Comment