Introduction
This helps you use a default value when a variable is empty or not set, so your script keeps working smoothly.
${variable:-default_value}echo "${name:-Guest}"filename=${file:-default.txt}
echo "$filename"echo "Welcome, ${user:-friend}!"#!/bin/bash # Variable 'color' is not set # Use default value 'blue' if 'color' is unset or null chosen_color=${color:-blue} echo "The chosen color is $chosen_color"
${var:-default} do in a bash script?${var:-default}var if it is set and not empty; otherwise, use default.var is changedvar, it only provides a fallback value for use.var if set; otherwise, it uses default without changing var. -> Option Avar is empty or unset [OK]name or use "Guest" if name is empty or unset?${var:-default} prints var if set; otherwise, prints default.Guest only if name is set. echo ${name?Guest} throws error if name is unset. Only echo ${name:-Guest} prints name or "Guest" safely.unset user
user=""
echo "User: ${user:-anonymous}"user is first unset, then set to an empty string.user is empty (empty string counts as unset for :-), the expression uses the default "anonymous".echo "Name: ${name-default}"${name-default} uses default only if name is unset, but not if empty.${name:-default} is needed.path if set and not empty, otherwise print "/usr/local/bin". But if path is set to an empty string, you want to treat it as unset. Which command correctly does this?path if it is set and not empty; otherwise, print the default "/usr/local/bin".${path:-default} uses default if path is unset or empty. ${path-default} only uses default if unset, not empty. ${path:=default} assigns default to path. ${path:+default} prints default only if path is set.Pass the test and this pattern moves unknown