bash_profileがログインを介して取得されるのか、スクリプトで取得されるのかを判断しますか?

bash_profileがログインを介して取得されるのか、スクリプトで取得されるのかを判断しますか?

ファイルに設定されている環境変数に依存する多くのスクリプトがあります.bash_profile

また、サーバーにログインしたときに特定のメッセージを表示したかったのですが、それも追加しました.bash_profile。ただし、スクリプトが呼び出されたときにこのメッセージを表示したくありません。

を使用することもできますが、source ~/.bash_profile > /dev/null 2>&1それを行うにはすべてのスクリプトをチェックする必要があるので退屈です。したがって、スクリプトのソースを確認する方法があるかどうか疑問に思います。

私の目標は次のとおりです(医師コード)。

#FROM_TERMINAL should be set to 1 if ran by the user (logging into the server) - otherwise it stays empty.
if [[ $FROM_TERMINAL = 1 ]]; then
    echo "some message"
else
    :
fi

これを行うエレガントな方法はありますか?

ありがとうございます!

ベストアンサー1

では、man bash次のように言います。

An interactive shell is one started without non-option arguments (unless -s is specified) and without the -c option whose standard input and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option.
PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state.

この$-フラグにはシェルオプションセットが含まれており、その説明は次のとおりです。 https://tldp.org/LDP/abs/html/internalvariables.html

$-次のように変数の内容を確認します。

$ echo "$-"
himBHs

次のように設定されていることを確認してくださいi

if [[ $- == *i* ]]
then
    # I was called interactively, do the echoing etc.
fi

$PS1varが設定されていることを確認することもできますが、この方法は信頼性が低下します。バラよりhttps://tldp.org/LDP/abs/html/intandnonint.html#IITEST

おすすめ記事