4.3 パイプとリダイレクト
Pipes and Redirection
パイプ(|)はコマンドの出力を次のコマンドの入力に接続する。リダイレクトはファイルへの入出力を制御する。
パイプ
@startuml !theme plain skinparam backgroundColor #FEFEFE rectangle "cmd1" as C1 #DBEAFE rectangle "cmd2" as C2 #D1FAE5 rectangle "cmd3" as C3 #FEF3C7 C1 -right-> C2 : stdout → stdin C2 -right-> C3 : stdout → stdin note top of C1 cat file.txt end note note top of C2 grep 'error' end note note top of C3 wc -l end note note bottom cat file.txt | grep 'error' | wc -l → errorを含む行数をカウント end note @enduml
図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
リダイレクト
@startuml
!theme plain
skinparam backgroundColor #FEFEFE
rectangle "プロセス" as Process #DBEAFE {
rectangle "stdin (0)" as Stdin
rectangle "stdout (1)" as Stdout
rectangle "stderr (2)" as Stderr
}
rectangle "キーボード" as KB #E5E7EB
rectangle "画面" as Screen #E5E7EB
rectangle "ファイル" as File #D1FAE5
KB --> Stdin : デフォルト
Stdout --> Screen : デフォルト
Stderr --> Screen : デフォルト
note right of File
< : 入力元をファイルに
> : 出力先をファイルに
2> : エラー出力をファイルに
end note
@enduml
図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.
[2] man xargs - build and execute command lines from standard input.