Bash Shell Parameter Substitution
Bash Shell Parameter Substitution
Bash Shell Parameter Substitution
Syntax
You can use variables to store data and con guration options. For example:
dest="/backups"
echo "$dest"
OR
printf "$dest\n"
The parameter name or symbol such as $dest to be expanded may be enclosed in braces
${parameter:-defaultValue}
var=${parameter:-defaultValue}
If parameter not set, use defaultValue. In this example, your shell script
takes arguments supplied on the command line. You’d like to provide
default value so that the most common value can be used without
needing to type them every time. If variable $1 is not set or passed, use
root as default value for u:
u=${1:-root}
_mkdir(){
local d="$1" # get dir name
local p=${2:-0755} # get permission, set default to 0755
[ $# -eq 0 ] && { echo "$0: dirname"; return; }
[ ! -d "$d" ] && mkdir -m $p -p "$d"
}
Use this substitution for creating failsafe functions and providing missing command line
arguments in scripts.
${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
Sample outputs:
vivek
Now, assign a value foo to the $USER variable if doesn’t already have one:
echo ${USER:=foo}
Sample outputs:
vivek
unset USER
echo ${USER:=foo}
Sample outputs:
foo
This make sure you always have a default reasonable value for your script.
Please note that it will not work with positional parameter arguments:
If the variable is not de ned or not passed, you can stop executing the Bash script with
the following syntax:
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:
#!/bin/bash
# Purpose: Wrapper script to setup Nginx Load Balancer
# Author: Vivek Gite
_root="/nas.pro/prod/scripts/perl/nginx"
_setup="${_root}/createnginxconf.pl"
_db="${_root}/database/text/vips.db"
_domain="${1:?Usage: mknginxconf domainName}" ### die if domainName is
[ ! -f $_db ] && { echo "$0: Error $_db file not found."; exit 1; }
line=$(grep "^${_domain}" $_db) || { echo "$0: Error $_domain not found in
# Build query
d="$f1:$ssl:$f4"
IFS=','
ips=$f3
# Call our master script to setup nginx reverse proxy / load balancer (LB)
$_setup "$d" $ips
If $2 is not set display an error message for $2 parameter and run cp command on y as
follows:
#!/bin/bash
_file="$HOME/.input"
_message="Usage: chkfile commandname"
$_cmd "$_file"
${#variableName}
echo ${#variableName}
len=${#var}
# Add user
/sbin/useradd -s /sbin/nologin -m "${_fuser}"
echo "${_fpass}" | /usr/bin/passwd "${_fuser}" --stdin
Each Linux or UNIX command returns a status when it terminates normally or abnormally.
You can use command exit status in the shell script to display an error message or take
some sort of action. In above example, if getent command is successful, it returns a code
which tells the shell script to display an error message. 0 exit status means the command
was successful without any errors. $? holds the return value set by the previously
executed command.
${var#Pattern}
${var##Pattern}
You can strip $var as per given pattern from front of $var. In this example remove /etc/
part and get a lename only, enter:
f="/etc/resolv.conf"
echo ${f#/etc/}
The rst syntax removes shortest part of pattern and the second syntax removes the
longest part of the pattern. Consider the following example:
_version="20090128"
_url="http://dns.measurement-factory.com/tools/dnstop/src/dnstop-${_versio
You just want to get lename i.e. dnstop-20090128.tar.gz, enter (try to remove shortest
part of $_url) :
echo "${_url#*/}"
Sample outputs:
/dns.measurement-factory.com/tools/dnstop/src/dnstop-20090128.tar.gz
echo "${_url##*/}"
Sample outputs:
dnstop-20090128.tar.gz
#!/bin/bash
_self="${0##*/}"
echo "$_self is called"
#!/bin/bash
# Purpose: Display jail info as per softlink
# Author: Vivek Gite
_j="$@"
for j in $_j
do
export _DOMAIN_NAME=$j
source functions.sh
init_jail
# call appropriate functions as per script-name / softlink
case $_self in
uploaddir.info) echo "Upload dir for $j: $(get_domain_uplo
tmpdir.info) echo "/tmp dir for $j: $(get_domain_tmp_dir)"
mem.info) echo "$j domain mem usage (php+lighttpd): $(get_
cpu.info) echo "$j domain cpu usage (php+lighttpd): $(get_
user.info) echo "$j domain user and group info: $(get_doma
diskquota.info) echo "$j domain disk quota info (mysql+dis
*) warn "Usage: $_self"
esac
done
# ./mem.info example.org
# ./cpu.info example.com example.net
${var%pattern}
${var%%pattern}
Exactly the same as above, except that it applies to the back of $var. In this example
remove .tar.gz from $FILE, enter:
FILE="xcache-1.3.0.tar.gz"
echo ${FILE%.tar.gz}
Sample outputs:
xcache-1.3.0
Rename all *.perl les to *.pl using bash for loop as Apache web server is con gured to
only use .pl le and not .perl le names:
for p in /scripts/projects/.devl/perl/*.perl
do
mv "$p" "${p%.perl}.pl"
done
#!/bin/bash
# Usage: Build suhosin module for RHEL based servers
# Author: Vivek Gite
# ----
# Set default value for $2
VERSION="-${2:-0.9.31}"
URL="http://download.suhosin.org/suhosin${VERSION}.tgz"
vURL="http://download.suhosin.org/suhosin${VERSION}.tgz.sig"
# Download software
wget $URL -O "${DLHOME}/$FILE"
wget $vURL -O "${DLHOME}/$vFILE"
# Extract it
tar -zxvf $FILE
cd "$DEST"
${varName/Pattern/Replacement}
${varName/word1/word2}
${os/Unix/Linux}
echo "${x/unix/linux}"
out="${x/unix/linux}"
echo "${out}"
out="${x//unix/linux}"
install_php_modules(){
# get jail name
local n="${_chrootbase}/${d##/}"
local p=""
local ini=""
# enable only ${_php_modules_enabled} php modules and delete other
for i in $_php_modules/*
do
p="${i##*/}"
ini="$n/etc/php.d/${p/so/ini}"
# find out if module is enabled or not
if [[ ${_php_modules_enabled} = *${p}* ]]
then
[ "$VERBOSE" == "1" ] && echo " [+] Enabling php m
$_cp -f "$i" "$n/${_php_modules##/}" ## instal
copy_shared_libs "$i" ## get s
else
[ -f "${ini}" ] && $_rm -f "${ini}" ## if ol
fi
done
}
${parameter:offset}
${parameter:offset:length}
${variable:position}
var=${string:position}
base="/backup/nas"
file="/data.tar.gz"
#### strip extra slash from $file ####
path="${base}/${file:1}"
Extract craft word only:
x="nixcraft.com"
echo ${x:3:5}"
phone="022-124567887"
# strip std code
echo "${phone:4}"
Want to get the names of variables whose names begin with pre x? Try:
VECH="Bus"
VECH1="Car"
VECH2="Train"
echo "${!VECH*}"
name="vivek"
# Turn vivek to Vivek (only first character to uppercase)
echo "${name^}"
# Turn vivek to VIVEK (uppercase)
echo "${name^^}"
echo "Hi, $USERNAME"
echo "Hi, ${USERNAME^}"
echo "Hi, ${USERNAME^^}"
# Convert everything to lowercase
dest="/HOME/Vivek/DaTA"
echo "Actual path: ${dest,,}"
# Convert only first character to lowercase
src="HOME"
echo "${src,}"
dest="Home"
echo "${dest,H}"
dest="Fhome"
echo "${dest,H}"
For your ready references here are all your handy bash parameter substitution operators.
Try them all; enhance your scripting skills like a pro:
${var:num1:num2} Substring
${var,}
Convert rst character to lowercase.
${var,pattern}
${var,,}
Convert all characters to lowercase.
${var,,pattern}
${var^}
Convert rst character to uppercase.
${var^pattern}
${var^^}
Convert all character to uppercase..
${var^^pattern}
References:
Learn more
Posted by: Vivek Gite
The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for
the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin,
Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.
I have a small favor to ask. More people are reading the nixCraft. Many of you
block advertising which is your right, and advertising revenues are not
suf cient to cover my operating costs. So you can see why I need to ask for
your help. The nixCraft takes a lot of my time and hard work to produce. If
everyone who reads nixCraft, who likes it, helps fund it, my future would be
more secure. You can donate as little as $1 to support nixCraft:
31 comment
Thanks.
These are POSIX shell expansions and bash/ksh93 extensions. They do not apply to
tcsh (which should not be used for scripting).
I hate to go offtopic as well, but I love the Internet Explorer 9 ad on the right….. wtf?
Ads comes from various sources. This is the only way to cover the cost of hosting,
CDN and bandwidth. Hope this helps!
So you got post back but deleted all comments? How come?
Backups are done ones a day. This post was restored from my local open of ce org
cache le. There is not much I can do to restore all 12-13 comments including yours.
What a great tutorial and reference. I can never remember the syntax when I need it. Will
de nitely be bookmarking this one.
Great tips! There are some functionalities I didn’t even know existed.
thiagoc October 18, 2010 at 2:11 am
cp “${y}” “${y/.conf/.conf.bak}”
cp “${y}”{,.bak}
cp "$y" "$y.bak"
cp ${y,.bak}
$ y=HELLO
$ echo "${y,}"
hELLO
$ echo "${y,,}"
hello
You’re right. Not sure where my brain was that day. One would I assume I
tested it before commenting, but it doesn’t seem to do anything. No error
or warning either. That’s bash for you. 😛
good tutorial,
thanks
Thanks for this excellent HowTo! One minor correction: sed ‘s/unix/linux’ <<<$x should be
sed 's/unix/linux/g' <<<$x
or equivalent to allow user to set permissions other than the default 0755 value?
Tom June 24, 2013 at 6:35 pm
to inform user to set permissions other than the default 0755 value if desired?
Something interesting to note on the substring syntax is that you can address the offset
backwards as well. I am not sure about how portable this syntax is, but I have found it
very useful:
echo “${VAR: -4}” # Prints the last 4 characters, note the space between : and – in this
example.
echo “${VAR:1:-1}” # The space is optional on the second offset, but not the rst
${bam:=value}
-bash: value: command not found
maedox September 25, 2014 at 11:07 am
@khoan, yes, what did you expect? There is no command named ‘value’. Put echo in
front and it should output ‘value’ unless $bam is already set.
Ikem, all the POSIX expansions (#1..#4) will work in dash (but not the shopt command).
N ext post:
Tagged as: assignment operator, command line arguments, command substitution, default shell, parameter
expansion, shell variables
@2000-2019 nixCraft. All rights reserved.
PRIVACY
TERM OF SERVICE
CONTACT/EMAIL
DONATIONS
SEARCH