2011-11-20 22 views
5

Mam plik tekstowy, w którym każda linia jest listą argumentów, które chcę przekazać skryptowi nodejs. Poniżej znajduje się przykład pliku plik.txt:przekazywanie cytowanych argumentów do węzła za pomocą skryptu powłoki?

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

Dla dobra demonstracja za skrypt węzeł jest po prostu:

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

chcę uruchomić ten skrypt węzła dla każdego wiersza w pliku tekstowym, więc dokonaniu tego skryptu bash, run.sh:

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

Kiedy uruchomić ten skrypt bash, to co mam:

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

Ale kiedy tylko uruchomić skrypt węzła bezpośrednio uzyskać oczekiwany wynik:

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

Co tu się dzieje? Czy istnieje bardziej węzłowy sposób na zrobienie tego?

Odpowiedz

9

Co się tutaj dzieje, to że $line nie jest wysyłany do twojego programu w sposób, jakiego oczekujesz. Jeśli dodasz flagę -x na początku skryptu (na przykład #!/bin/bash -x), możesz zobaczyć każdą linię, która jest interpretowana, zanim zostanie wykonana. W przypadku skryptu dane wyjściowe wyglądają następująco:

$ ./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 

Zobacz wszystkie te pojedyncze cytaty? Z pewnością nie są tam, gdzie chcesz. Możesz użyć numeru eval, aby wszystko było poprawnie cytowane. Ten skrypt:

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

Daje mi poprawny wynik:

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

oto wyjście -x też, dla porównania:

$ ./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 

Widać, że w tym przypadku, po eval krok, cytaty znajdują się w miejscach, w których chcesz je widzieć. Oto dokumentację eval z bash(1) man page:

eval [arg ...]

The args są czytane i łączone ze sobą w jednym poleceniu. To polecenie jest następnie odczytywane i wykonywane przez powłokę, a jego kod wyjścia jest zwracany jako wartość eval. Jeśli nie ma args lub tylko zerowe argumenty, eval zwraca 0.

+0

dzięki! to wystarczyło – Rafael

Powiązane problemy