4.3 パイプとリダイレクト

Pipes and Redirection

パイプ(|)はコマンドの出力を次のコマンドの入力に接続する。リダイレクトはファイルへの入出力を制御する。

パイプ

パイプの動作

図1: パイプによるコマンド連携

# 基本的なパイプ
cat file.txt | grep 'error'

# 複数パイプ
cat access.log | grep 'GET' | awk '{print $1}' | sort | uniq -c | sort -rn | head -10

# プロセス検索
ps aux | grep nginx

# ディスク使用量トップ10
du -sh * | sort -rh | head -10

リダイレクト

標準入出力

図2: 標準入出力とリダイレクト

記号 説明
> 上書き出力 ls > list.txt
>> 追記出力 echo "line" >> file.txt
< ファイルから入力 sort < data.txt
2> 標準エラーをリダイレクト cmd 2> error.log
&> stdout + stderrを出力 cmd &> all.log
2>&1 stderrをstdoutへ cmd > out.log 2>&1
# 出力をファイルに保存
ls -la > filelist.txt

# 追記
echo "new line" >> file.txt

# エラーを別ファイルに
find / -name "*.conf" 2> /dev/null

# 出力とエラーを同じファイルに
./script.sh > output.log 2>&1

# 出力を捨てる
command > /dev/null 2>&1

ヒアドキュメント

# 複数行入力
cat << EOF
line 1
line 2
line 3
EOF

# ファイル作成
cat << EOF > config.txt
server=localhost
port=8080
EOF

# コマンドに入力
mysql -u root << EOF
USE database;
SELECT * FROM users;
EOF

xargs

# 検索結果を引数に
find . -name "*.txt" | xargs grep 'pattern'

# 並列実行
find . -name "*.jpg" | xargs -P4 -I{} convert {} -resize 50% small_{}

# 確認付き
echo "file1 file2" | xargs -p rm

# 1つずつ処理
cat files.txt | xargs -n1 echo
出典
[1] Bash Reference Manual - Redirections.
[2] man xargs - build and execute command lines from standard input.