Set Default Value to Shell Script Variable
If parameter is unset or null Set Default Value
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
If parameter is unset then Set Default Value
${parameter-word}
If parameter is unset, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
let's create a script and execute it for practice purpose.
#!/bin/bash
read -p " please enter your name " name
name=${name:-World}
echo "Hello ${name^}"
yourname=${unsetvariable-Manish}
echo $yourname
myname=""
mytestname=${myname:-kali}
echo ${mytestname}
output:
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./defaultvalue.sh
please enter your name Gaurav
Hello Gaurav
Manish
kali
Check A Variable is set or not using below script
#!/bin/bash
# name="gaurav"
: ${1:?" please set variable values. "}
echo "i am here."
output:
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./if-variable-not-set.sh Gaurav
i am here.
┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./if-variable-not-set.sh
./if-variable-not-set.sh: line 4: 1: please set variable values.