Why is the value of this line running in a bash script?

Why does this script execute a line in an 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 starting with outputs sh script.sh:

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

ps first try shell script
thanks

+3
source share
2 answers

You are trying to execute a command [hello. Put a space after [so that it is recognized as a test.

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

Assuming the line "echo first" is for debugging only, you can achieve the same thing:

STRING = $ STRING $ {STRING: +} hello

(That is, the above line will give the same result as the if statement, but there will be no echo "first")

'$ {STRING: +}' , $STRING null, .

+2

Source: https://habr.com/ru/post/1736734/


All Articles