9

一部のファイルのレコードを処理するスクリプトがあります。通常、1〜2時間かかります。実行中は、処理されたレコード数の進行状況を出力します。

さて、私がやりたいのは、それがで実行されているときnohup、進行状況を印刷したくないということです。手動で実行した場合にのみ進行状況を出力する必要があります。

私の質問は、bashスクリプトがで実行されているかどうかをどうやって知るのnohupですか?

コマンドが。であるとしnohup myscript.sh &ます。nohupスクリプトで、 fromコマンドラインを取得するにはどうすればよいですか?使ってみました$0が、myscript.sh

4

5 に答える 5

9

Checking for file redirections is not robust, since nohup can be (and often is) used in scripts where stdin, stdout and/or stderr are already explicitly redirected.

Aside from these redirections, the only thing nohup does is ignore the SIGHUP signal (thanks to Blrfl for the link.)

So, really what we're asking for is a way to detect if SIGHUP is being ignored. In linux, the signal ignore mask is exposed in /proc/$PID/status, in the least-significant bit of the SigIgn hex string.

Provided we know the pid of the bash script we want to check, we can use egrep. Here I see if the current shell is ignoring SIGHUP (i.e. is "nohuppy"):

$ egrep -q "SigIgn:\s.{15}[13579bdf]" /proc/$$/status && echo nohuppy || echo normal
normal
$ nohup bash -c 'egrep -q "SigIgn:\s.{15}[13579bdf]" /proc/$$/status && echo nohuppy || echo normal'; cat nohup.out
nohup: ignoring input and appending output to `nohup.out'
nohuppy
于 2016-02-25T21:28:55.983 に答える
1

1つの方法ですが、実際には移植性はありませんが、readlinkをオンにして、nohup.out/proc/$$/fd/1で終わるかどうかをテストすることです。

あなたがターミナルにいると仮定しますpts0(実際には関係ありません、ただ結果を表示できるようにするためです):

#!/bin/bash

if [[ $(readlink /proc/$$/fd/1) =~ nohup.out$ ]]; then
    echo "Running under hup" >> /dev/pts/0
fi

しかし、このような問題に対する従来のアプローチは、出力が端末であるかどうかをテストすることです。

[ -t 1 ]
于 2013-02-28T17:00:57.353 に答える
1

STDOUTが端末に関連付けられているかどうかを確認できます。

[ -t 1 ]
于 2013-02-28T16:50:19.873 に答える
0

君たちありがとう。STDOUT を確認することをお勧めします。別の方法を見つけるだけです。それはttyをテストすることです。test tty -s 戻りコードをチェックします。0 の場合、端末で実行されています。1 の場合は、nohup で実行されています。

于 2013-02-28T17:09:14.817 に答える