2010-03-12 5 views
3

Pourquoi ce script exécution de la chaîne dans l'instruction if:Pourquoi la valeur de cette chaîne, dans un script bash, est-elle en cours d'exécution?

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

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

echo $STRING 

lorsqu'il est exécuté avec sh script.sh sorties:

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. première tentative d'un script shell
grâce

Répondre

6

Vous essayez d'exécuter la commande [hello. Mettez un espace après [ afin qu'il soit reconnu comme un test.

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

merci. je vais apprendre le rubis à la place:) – Ross

2

En supposant que la ligne « écho d'abord » est simplement pour le débogage, vous pouvez obtenir la même chose avec:

 
STRING=$STRING${STRING:+ }hello 

(C'est, la ligne ci-dessus produira le même résultat que votre si instruction, mais n'échangera pas 'first')

L'expression '$ {STRING: +}' évalue à rien si $ STRING est vide ou null, et il évalue à un espace sinon.

Questions connexes