Substring of a variable
The substring of a
variable can be extracted with
${var:start}
or
${var:start:end}
:
#!/bin/bash
zeroToNine=0123456789
echo ${zeroToNine:0}
# 0123456789
echo ${zeroToNine:7}
# 789
echo ${zeroToNine:5:4}
# 5678
echo ${zeroToNine: -3}
# 789
echo ${zeroToNine: -6: 2}
# 45
echo ${zeroToNine: -4:-1}
# 678
array=(0 1 2 3 4 5 6 7 8 9)
echo ${array[@]:4:3}
# 4 5 6
A substring can also be realized with
expr $var $start $len
Replace/change parts of the variable value
${var/pattern/replacement}
returns the value of the variable with pattern
replaced by replacement
.
The variable itself does not change.
#!/bin/bash
var="foo bar baz"
echo ${var/a*/REPLACED}
# foo bREPLACED
echo $var
# foo bar baz
TODO
# Assignment might occur in the form ${VAR=VALUE} or ${VAR:=VALUE}
var1=foo
nullVar1=
# Substitute if null or undefined {
# first batch: with colon {
# (assign if not set or null)
echo ${var1:=abc}
# foo
echo $var1
# foo
echo ${nullVar1:=def}
# def
echo $nullVar1
# def
echo ${unset1:=ghi}
# ghi
echo $unset1
# ghi
# }
echo
# second batch: without colon {
# (assign if not set)
var2=bar
nullVar2=
echo ${var2=jkl}
# bar
echo $var2
# bar
echo ${nullVar2=mno}
#
echo $nullVar2
#
echo ${unset2=pqr}
# pqr
echo $unset2
# pqr
# }
# }
#!/bin/bash
car_one=Mercedes
car_two=BMW
car_three=Porsche
for v in ${!car*}; do
echo $v
done
# car_one
# car_three
# car_two
#!/bin/bash
# mnemonic: # is on the left, % on the right side of the $ key.
# hence # deletes from the left, % from the right side.
var="foo bar baz"
# delete shortest possible match from the left
echo ${var#*a}
# r baz
# delete longest possible match from the left
echo ${var##*a}
# z
# delete shortest possible match from the right
echo ${var%a*}
# foo bar b
# delete longest possible match from the right
echo ${var%%a*}
# foo b
# Substitution might occur in the form ${VAR-SUBST} or ${VAR:-SUBST}
var1=foo
nullVar1=
# Substitute if null or undefined {
# first batch: with colon {
# (substitue if set and non-null)
echo ${var1:+abc}
# abc
echo ${nullVar1:+def}
#
echo ${unset1:+ghi}
#
# }
echo ----------
# second batch: without colon {
# (substitue if set)
var2=foo
nullVar2=
echo ${var2+jkl}
# jkl
echo ${nullVar2+mno}
# mno
echo ${unset2+pqr}
#
# }
# }
# Substitution might occur in the form ${VAR-SUBST} or ${VAR:-SUBST}
var=foo
nullVar=
# Substitute if null or undefined {
# first batch: with colon {
# (substitue if not set or null)
echo ${var:-abc}
# foo
echo ${nullVar:-def}
# def
echo ${unset:-ghi}
# ghi
# }
# second batch: without colon {
# (subsitue if not set)
echo ${var-jkl}
# foo
echo ${nullVar-mno}
#
echo ${unset-pqr}
# pqr
# }
# }
# The following line is written to std err
exit_program=${unset?Exit the program because \'unset\' is not set}
echo "This line is not printed..."