LoginSignup
12

More than 5 years have passed since last update.

Bash: 変数のデフォルト値の定義は`${変数名:-初期値}`でやる

Posted at

Bashで変数のデフォルト値をセットするには、${変数名:-初期値}という書き方でやります。

#!/bin/bash
echo "message: ${MESSAGE}"
echo "message: ${MESSAGE:-hello}"

# ここでは、$MESSAGEは未定義。
MESSAGE=${MESSAGE:-bye} # 初期値を変数化するときは再代入する
echo "message: ${MESSAGE}"
echo "message: ${MESSAGE:-hello}"

output:

message: 
message: hello
message: bye
message: bye

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12