バックグラウンドプロセスで$(tty)をエコーし​​ます。

バックグラウンドプロセスで$(tty)をエコーし​​ます。

なぜ何も印刷されないのですか?

bash -c '(while echo "not printing" ; do sleep 1; done) > "$(tty)" & sleep 10'

たとえば、次のようになります。

bash -c '(while echo "is printing" ; do sleep 1; done) > "$(tty)" && true'

ベストアンサー1

最初のコマンドを実行し、一時ディレクトリから実行してみましょう。

mkdir eg1    # Create temporary directory
cd eg1       # ...and change to it
ls           # No output (obviously, no files)

bash -c '(while echo "not printing" ; do sleep 1; done) > "$(tty)" & sleep 10'

しかし、今目次を見てください。

ls -l
-rw-r--r--+ 1 roaima roaima 1040 Jun  6 23:05 not a tty

ここで起こるのは、端末が接続された状態で実行されるときなど、コマンドttyが端末装置に報告され、他の場合にはメッセージが表示されることです。 background() でサブシェルとして実行されると、ターミナルデバイスがないため、出力が 。/dev/pty0not a tty&( … )not a tty

2番目のケースでは、サブシェルがバックグラウンドで実行されないことを除いて、すべてが非常に似ています。

bash -c '(while echo "is printing" ; do sleep 1; done) > "$(tty)" && true'

この場合、ttyフォアグラウンドで実行され、現在の端末のデバイス名を返すことができるため、画面に出力を表示できます。

これは&&論理コネクタで、2 番目のコマンドは、最初のコマンドが「成功」(値 0) 終了ステータスを返す場合にのみ実行されます。&前のコマンドがバックグラウンドで独立して実行されるように指示するthisと混同しないでください。

# Run the ( ... ) in the background concurrently with the foreground process
( sleep 1; echo background ) & echo foreground; wait

[1] 32301
foreground
background
[1]+  Done                    ( sleep 1; echo background )

# Run the ( ... ) and then if it's successful execute the next statement
( sleep 1; echo background ) && echo foreground; wait

background
foreground

/dev/tty達成したい目標に応じて、使用したり出力をまったくリダイレ​​クトしたりしないことを検討することもできます。

おすすめ記事