Skip to main content

The $ character is used for parameter expansion, and command substitution. You can use it for manipulating and/or expanding variables on demands without using external commands such as sed or awk.

# -----------------------------------------------------------------------------
# Bash: Assign Output of Shell Command To Variable
#   http://www.cyberciti.biz/faq/unix-linux-bsd-appleosx-bash-assign-variable-command-output/
# -----------------------------------------------------------------------------

##
# 1: Getting Up Default Shell Variables Value
##

# SYNTAX:

${parameter:-defaultValue}
var=${parameter:-defaultValue}

# Consider the following example:

#!/bin/bash
_jail_dir="${1:-/home/phpcgi}"
echo "Setting php-cgi at ${_jail_dir}..."

# rest of the script ...
# You can now run this script as follows:

./script.sh /jail              # <--- set php jail at /jail dir
./script.sh /home/httpd/jail   # <---- set php jail at /home/httpd/jail dir
./script.sh                    # <--- set php jail dir at /home/phpcgi (default)

##
# 1.1: Setting Default Values
##

# SYNTAX:

${var:=value}
var=${USER:=value}

# The assignment (:=) operator is used to assign a value to the variable if
# it doesn't already have one. Try the following examples:

echo $USER
# outputs => vivek

# Now, assign a value foo to the $USER variable if doesn't already have one:

echo ${USER:=foo}
# outputs => vivek

# Unset value for $USER:

unset USER
echo ${USER:=foo}
# outputs => foo

##
# Tip: ${var:-defaultValue} vs ${var:=defaultValue}
###

# Please note that it will not work with positional
# (http://bash.cyberciti.biz/guide/How_to_use_positional_parameters)
# parameter arguments:

var=${1:=defaultValue}    ### FAIL with an error cannot assign in this way
var=${1:-defaultValue}    ### Perfect

##
# 2: Display an Error Message If $VAR Not Passed
##

# If the variable is not defined or not passed, you can stop executing the
# Bash script with the following syntax:

${varName?Error varName is not defined}
${varName:?Error varName is not defined or is empty}
${1:?"mkjail: Missing operand"}

# MESSAGE="Usage: mkjail.sh domainname IPv4"   ### define error message
# _domain=${2?"Error: ${MESSAGE}"}             ### you can use $MESSAGE too

# This is used for giving an error message for unset parameters.
# In this example, if the $1 command line arg is not passed, stop executing
# the script with an error message:

_domain="${1:?Usage: mknginxconf domainName}"

##
# Complete article here ...
# http://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html
##