yuuka_maniaの日記: シェルスクリプトで標準入出力が何なのか判断する 2
日記 by
yuuka_mania
そういえばどうすればいいのか、わからなかったので、メモ。
% cat ./foo.sh
#!/bin/sh -u
[ -t 0 ] && echo "tty stdin"
[ -p /dev/stdin ] && echo "pipe stdin"
[ -f /dev/stdin ] && echo "file stdin"
[ -t 1 ] && echo "tty stdout"
[ -p /dev/stdout ] && echo "pipe stdout"
[ -f /dev/stdout ] && echo "file stdout"
[ -t 2 ] && echo "tty stderr"
[ -p /dev/stderr ] && echo "pipe stderr"
[ -f /dev/stderr ] && echo "file stderr"
% ./foo.sh
tty stdin
tty stdout
tty stderr
% echo a | ./foo.sh |& cat
pipe stdin
pipe stdout
pipe stderr
% echo a | ./foo.sh > /tmp/a
% cat /tmp/a
pipe stdin
file stdout
tty stderr
% ./foo.sh < /tmp/a 2> /tmp/a.stderr
file stdin
tty stdout
file stderr
テスト追加 (スコア:0)
tty stdin
file stdout
file stderr
% ./foo.sh 2>/tmp/a.stderr >&2
tty stdin
file stdout
file stderr
% ./foo.sh 2>&1 >/tmp/a
tty stdin
file stdout
tty stderr
↑stderrはstdoutに出るけど、ttyか否かしか識別できないからね……
tty stdinは、stdin ttyのような順のほうが、
なんでtty stdoutにならないの?と誤解を招かないのでヨサゲ。
/proc/[PID]/fd/{0,1,2} を使う方法 (スコア:0)
linux 限定だけど /proc/[PID]/fd/{0,1,2} を使う方法もありますよ
$ cat hoo.sh
ls -la /proc/$$/fd/
$ bash ./hoo.sh
$ bash ./hoo.sh poo.txt
$ cat poo.txt
$ bash ./hoo.sh foo.txt
$ cat foo.txt
という感じ