views:

79

answers:

2

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

+4  A: 

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
Johannes Schaub - litb
thanks. i'm going to learn ruby instead : )
Ross
+2  A: 

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.

William Pursell