Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 760
Ross Avatar asked Jan 19 '26 10:01

Ross


1 Answers

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
like image 174
Johannes Schaub - litb Avatar answered Jan 22 '26 01:01

Johannes Schaub - litb