Site cover image

fhhm’s blog

⌨️パラメータ展開とコマンド置換

パラメータ展開(Parameter Expansion)

${}で、変数の内容を展開する構文。

変数から特定の要素を抽出したり、長さの取得をしたりする際に使用する。

コマンド置換(Command Substitution)

$()で、コマンドを実行し、結果を利用する構文。

コマンド実行結果の代入等で使用する。

それぞれの違い

パラメータ展開ではできるが、コマンド置換ではできない
  • 長さや要素の取得
s="string"

echo "Length is ${#s}"
# -> length is 6

echo "The last three chars is \"${s: -3}\""
# -> The last three chars is "ing"
コマンド置換ではできるが、パラメータ展開ではできない
  • コマンド実行結果の代入
d="2024/12/31"

year=$(echo $d | awk -F '/' '{print $1}')
echo "year is $year"
# -> year is 2024