$をどのように使用しますか?機能を確認するためにテストしますか?

$をどのように使用しますか?機能を確認するためにテストしますか?
    #!/bin/sh

function checkExit(){
    if test "$?" != "0"; then
      echo Command $1 exited with abnormal status
      exit 1;
    else echo $?
    fi
}

function echoThenRun () { # echo and then run the command
  echo $1
  $1
  ret=$?
  echo $ret
  return $ret
}
file=test_file
echo > $file
echoThenRun "test -f $file"
checkExit $file
echo "all right!"

スクリプトの実行結果:

$  ~/Downloads/test.sh 
test -f test_file
0
1 # why 1 here??
all right!

ベストアンサー1

現在行っている作業をより簡単に行う方法があります。set -x(またはset -o xtrace同じものを)使用すると、スクリプトは実行される前に各行を自動的にエコーします。

また、他のコマンドを実行すると、その$?コマンドの終了コードが置き換えられます。

すばやくテストして忘れてしまうだけでなく、他の作業を行う予定の場合は、変数にバックアップする必要があります。[実際には独自の終了コードを持つプログラムです。

set +xコマンドをエコーするために使用されます。

たとえば、

(
    set -x # Cause commands to echo, but ONLY inside of this (...)
    execute some command...
    # Any further commands in these parens will also echo.
)
# Command echoing will be OFF at this point because we're outside of the (...).
# Now, $? holds the exit code of the (...) which gets it from the
# exit code of the last command executed inside of it.
result=$?
if [ "$result" -ne 0 ]; then
    echo "Your command exited with non-zero status $result"
fi

これはstderrに印刷されます:

+ execute some command...

代わりにset +x

set +x後で次のコマンドを使用してコマンドエコーを無効にすることもできます。

set -x # Cause commands to echo
execute some command...
result=$?
set +x # Turn off command echoing

しかし、このアプローチはあまりきれいではなく、最終的にstderrで印刷されます。

+ execute some command...
+ result=127
+ set +x

おすすめ記事