便利な xargsコマンド
ファイルを ls で調べ
その結果見つけたものの中身を grep で検索
これでもできるけど
できれば一度にすませたい
でも
1 | sudo ls /etc/ssh/ *config | grep -H key |
としても結果はでてこない
理由はls コマンドの結果は
標準出力、つまり画面に表示なので
パイプで流した文字列を引数にする必要がある
なので まずは while 文で調べるようにする
1 | ls /etc/ssh/ *config | while read f; do sudo grep -H key $f; done |
最初の
1 | ls /etc/ssh/ *config | while read f |
で ls コマンドの結果を、変数f に格納
スクリプトの場合、$変数名でアクセスできるので
1 | do sudo grep -H key $f; done |
でその結果のファイルパスを引数にして
grep コマンドで検索している
これよりもっと楽な方法として
xargs をつかう
これは、ほとんどの場合
パイプで渡された結果を受け取って
それを引数として、指定したコマンドで実行する
という使い方をする
例えば、今回の場合なら
ls コマンドででたファイルパスを
grep コマンドの引数にしたいので
1 | ls /etc/ssh/ *config | xargs sudo grep key |
とすれば
1 2 3 4 5 6 7 8 | /etc/ssh/sshd_config : #HostKey /etc/ssh/ssh_host_key /etc/ssh/sshd_config : #HostKey /etc/ssh/ssh_host_rsa_key /etc/ssh/sshd_config : #HostKey /etc/ssh/ssh_host_dsa_key /etc/ssh/sshd_config : # Lifetime and size of ephemeral version 1 server key /etc/ssh/sshd_config : #PubkeyAuthentication yes /etc/ssh/sshd_config : #AuthorizedKeysFile .ssh/authorized_keys /etc/ssh/sshd_config : # For this to work you will also need host keys in /etc/ssh/ssh_known_hosts /etc/ssh/sshd_config : # Change to no to disable s/key passwords |
と表示される
xargs コマンドは
ls や find で見つけた結果を処理するのに使える