-x呼び出しを使用して現在実行中のbashスクリプトがデバッグされているかどうかを確認するにはどうすればよいですか?

-x呼び出しを使用して現在実行中のbashスクリプトがデバッグされているかどうかを確認するにはどうすればよいですか?

launch.sh正しい所有者のファイルを生成するために他のユーザーとして実行されるスクリプトがあります。最初にスクリプトに渡された場合は、この呼び出しに-xを渡したいと思います。

if [ `whoami` == "deployuser" ]; then
  ... bunch of commands that need files to be created as deployuser
else
  echo "Respawning myself as the deployment user... #Inception"
  echo "Called with: <$BASH_ARGV>, <$BASH_EXECUTION_STRING>, <$->"
  sudo -u deployuser -H bash $0 "$@"  # How to pass -x here if it was passed to the script initially?
fi

私が読んでバッシュデバッグページしかし、元のスクリプトが-x

ベストアンサー1

bashコマンドラインに渡すことができる多くのフラグはsetフラグです。set実行時にこれらのフラグを切り替えることができるシェルが組み込まれています。たとえば、スクリプトを呼び出すことは、bash -x foo.sh本質的にスクリプトの上部で実行するのと同じです。set -x

setこれが組み込みシェルが担当していることがわかったら、私たちはどこを見るべきかを知ることができます。これでこれを行うhelp setと、次のような結果が得られます。

$ help set
set: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
...
      -x  Print commands and their arguments as they are executed.
...
    Using + rather than - causes these flags to be turned off.  The
    flags can also be used upon invocation of the shell.  The current
    set of flags may be found in $-.  The remaining n ARGs are positional
    parameters and are assigned, in order, to $1, $2, .. $n.  If no
    ARGs are given, all shell variables are printed.
...

したがって、ここで$-どのフラグが有効になっているかがわかります。

$ bash -c 'echo $-'
hBc

$ bash -x -c 'echo $-'
+ echo hxBc
hxBc

したがって、基本的には次のようにします。

if [[ "$-" = *"x"* ]]; then
  echo '`-x` is set'
else
  echo '`-x` is not set'
fi

ボーナスですべてのロゴをコピーしたい場合は、そうすることもできます。

bash -$- /other/script.sh

おすすめ記事