1

スクリプトが Bash によって実行されているかどうかを検出するために、以下をまとめました。

################################################################################
# Checks whether execution is going through Bash, aborting if it isn't. TinoSino

current_shell="$(
  ps                  `# Report a snapshot of the current processes` \
      -p $$           `# select by PID` \
      -o comm         `# output column: Executable namename` \
  |\
  paste               `# Merge lines of files ` \
      -s              `# paste one file at a time instead of in parallel` \
      -               `# into standard output` \
  |\
  awk                 `# Pick from list of tokens` \
      '{ print $NF }' `# print only last field of the command output`
)"

current_shell="${current_shell#-}" # Remove starting '-' character if present

if [ ! "${current_shell}" = 'bash' ]; then

  echo "This script is meant to be executed by the Bash shell but it isn't."
  echo 'Continuing from another shell may lead to unpredictable results.'
  echo 'Execution will be aborted... now.'

  return 0

fi

unset current_shell
################################################################################

あなたが私を CodeReview に送ることになるので、特にコード レビューをお願いしているわけではありません。私の質問は:

  • スクリプトの先頭に配置されたこの「実行ガード」が実際に確実に機能するかどうかをテストするにはどうすればよいですか?

zsh仮想マシンをインストールし、各マシンに、 などをインストールすることを考えてcshいますが、時間がかかりすぎます。これを行うためのより良い方法は?

すぐに間違いを見つけた場合は、私に指摘してください。足を振ってつぶされるのを待っているギラギラした虫は、つぶす必要があると思います。

4

2 に答える 2

6

これは次のように書くほうがよい

if [ -z "$BASH_VERSION" ]
then
   echo "Please run me in bash"
   exit 1
fi

テストに関しては、/etc/shells から非 bash シェルのリストを取得し、それぞれのシェルでスクリプトを実行して、エラー メッセージが表示されることを確認します。

于 2013-03-15T23:38:11.357 に答える