shでコロンとドル疑問符を結合する方法は?

shでコロンとドル疑問符を結合する方法は?

「コロン」と「ドル疑問符」を組み合わせて、スクリプトに引数がshあることを確認し、それを目的の変数に直接割り当てることができます。

cmd=${1:? "Usage: $0 {build|upload|log}"}

どのように機能し、実装の詳細をどこで見つけることができるかを段階的に説明できますか?たとえば、stderr

help() {
  echo $"Usage: $0 {build|upload|log}"
  exit 1
}
cmd=${1:? help}

なぜこれは不可能ですか?

ベストアンサー1

この内容は次のとおりです。変数拡張:

${parameter:?word}

If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

したがって、argumentスクリプトが実行されない場合、変数は標準出力に書き込まれ、cmdシェルhelpに返されます。

ただし、読み取りのみして実行するわけではありません。バックティックで囲むと実行され、Usage 関数が実行されます。

help() {
  echo "Usage: $0 {build|upload|log}"
}
cmd=${1:? `help`}

残念ながら、変数の拡張がそうするように設計されているので、これはまだstderrに表示されます。

次のこともできます。

cmd=${1:-help}
$cmd

おすすめ記事