ファイルから読み取ったコマンド ラインを変数に代入して実行したいのですが、単一のコマンドであれば問題ありません。| を使用すると機能しません。何か助けていただけますか? ありがとうございます
$ f="ls -1"
$ $f
a
a0
a1
a2
a3
b1
cfg
cfile
dfile
e
fcorreo.txt
log
logs
work
$ f="ls -1 | tail -1"
$ $f
ls: cannot access |: No such file or directory
ls: cannot access tail: No such file or directory
$ f='ls -1 | tail -1'
$ $f
ls: cannot access |: No such file or directory
ls: cannot access tail: No such file or directory
$ echo $f
ls -1 | tail -1
答え1
問題は、パイプ ( |
) がシェルによって実行される「メタ」コマンドであり、2 つの異なるコマンドを接続することです。2ls -1 | tail -1
つのコマンド (ls
とtail
) を実行し、シェル構造 ( |
) を使用して 2 つを接続します。(つまり、タイトル1つの変数内のコマンド間違いです。あなたの問題は本当に複数コマンド内のシングル変数)
いずれにせよ、解決策はシェルでコマンドを解析/実行することです。
f="ls -1 | tail -1"
sh -c "${f}"
あるいは、eval
新しいシェル プロセスをフォークせずに動作する を使用することもできます。
f="ls -1 | tail -1"
eval "${f}"
答え2
以下のような関数を使用できます。
f() { ls -1 | tail -1; }
例えば;
user@host $ f() { ls -1 | tail -1; }
user@host $ f
test.txt