2011-11-20 16 views
5

Ho un file di testo in cui ogni riga è un elenco di argomenti che voglio passare ad uno script nodejs. Ecco un esempio di file, file.txt:passando gli argomenti citati al nodo tramite script di shell?

"This is the first argument" "This is the second argument" 

Per l'amor di dimostrazione, lo script nodo è semplice:

console.log(process.argv.slice(2)); 

voglio eseguire questo script nodo per ogni riga nel file di testo, in modo da fatto questo script bash, run.sh:

while read line; do 
    node script.js $line 
done < file.txt 

Quando ho eseguito questo script bash, questo è quello che ottengo:

$ ./run.sh 
[ '"This', 
    'is', 
    'the', 
    'first', 
    'argument"', 
    '"This', 
    'is', 
    'the', 
    'second', 
    'argument"' ] 

Ma quando ho appena eseguito direttamente lo script del nodo ottengo i risultati attesi:

$ node script.js "This is the first argument" "This is the second argument" 
[ 'This is the first argument', 
    'This is the second argument' ] 

cosa sta succedendo qui? C'è un modo più nodo per farlo?

risposta

9

Che cosa sta succedendo qui è che $line non viene inviato al tuo programma nel modo previsto. Se aggiungi il flag -x all'inizio del tuo script (ad esempio #!/bin/bash -x, ad esempio), puoi vedere ogni riga mentre viene interpretata prima dell'esecuzione. Per il tuo script, l'output è il seguente:

$ ./run.sh 
+ read line 
+ node script.js '"This' is the first 'argument"' '"This' is the second 'argument"' 
[ '"This', 
    'is', 
    'the', 
    'first', 
    'argument"', 
    '"This', 
    'is', 
    'the', 
    'second', 
    'argument"' ] 
+ read line 

Vedi tutte quelle citazioni singole? Non sono sicuramente dove vuoi che siano. È possibile utilizzare eval per ottenere quotate correttamente. Questo script:

while read line; do 
    eval node script.js $line 
done < file.txt 

mi dà l'uscita corretta:

$ ./run.sh 
[ 'This is the first argument', 'This is the second argument' ] 

Ecco il -x uscita troppo, per il confronto:

$ ./run.sh 
+ read line 
+ eval node script.js '"This' is the first 'argument"' '"This' is the second 'argument"' 
++ node script.js 'This is the first argument' 'This is the second argument' 
[ 'This is the first argument', 'This is the second argument' ] 
+ read line 

Si può vedere che in questo caso, dopo la eval passo, le virgolette sono nei posti che vuoi che siano. Ecco la documentazione sul eval dal bash(1) man page:

eval [arg ...]

I args vengono letti e concatenati insieme in un unico comando. Questo comando viene quindi letto ed eseguito dalla shell e il suo stato di uscita viene restituito come valore di eval. Se non ci sono args, o solo argomenti nulli, eval ritorna 0.

+0

grazie! quello ha fatto il trucco – Rafael

Problemi correlati