パスワードを忘れた? アカウント作成
15628319 journal
日記

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

この議論は賞味期限が切れたので、アーカイブ化されています。 新たにコメントを付けることはできません。
  • by Anonymous Coward on 2022年04月18日 16時36分 (#4234705)
    % ./foo.sh >/tmp/a 2>&1
    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にならないの?と誤解を招かないのでヨサゲ。
  • by Anonymous Coward on 2022年04月19日 11時11分 (#4235255)

    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

    という感じ

typodupeerror

犯人は巨人ファンでA型で眼鏡をかけている -- あるハッカー

読み込み中...