2011-11-20 8 views
5

私は、各行がnodejsスクリプトに渡す引数のリストであるテキストファイルを持っています。ここでは例のファイル、file.txtは:私は、テキストファイル内のすべての行のために、このノードのスクリプトを実行したい引用符で囲まれた引数をシェルスクリプト経由でノードに渡しますか?

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

ので、私:

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

はデモンストレーションのために、ノードのスクリプトは、単純です

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

私はこのbashスクリプトを実行すると、これは私が得るものです::

このbashスクリプト、run.shを作りました

しかし、私はちょうど私が期待される出力を取得し、直接ノードのスクリプトを実行します。

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

ここで何が起こっていますか?これを行うには、より多くのノードの方法がありますか?

答えて

9

ここでは、$lineが期待どおりにプログラムに送信されないということが起こっています。スクリプトの冒頭に-xフラグを追加すると(たとえば#!/bin/bash -xなど)、すべての行が実行前に解釈されていることがわかります。スクリプトの場合、出力は次のようになります。

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

すべてのシングルクォートを参照してください。彼らは間違いなくあなたがそれらをしたい場所ではありません。 evalを使用すると、すべてを正しく引用することができます。このスクリプト:

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

は私に正しい出力を与える:

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

ここ-x出力は比較のために、あまりにもだ:

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

あなたはeval後、この場合にはそれを見ることができますステップ、引用符はあなたがそれらになりたい場所にあります。

evalの [引数 ...]

を読んで、単一のコマンドに一緒に連結されている引数

:ここbash(1) man pageからeval上のドキュメントがあります。このコマンドはシェルによって読み込まれて実行され、終了ステータスはevalの値として返されます。何引数、または唯一のヌル引数が、0

+0

感謝を返すはevalが存在しない場合は!それはトリックをした – Rafael

関連する問題