Sub stringing
name="James"echo $name ${name} # Same result
James Jamesecho ${name:0:2} ${name::2} # Print first 2 characters, can omit the zero
Ja Jaecho ${name::-2} # Remove n characters from the end
Jamecho ${name:(-2):1} # Start 2 characters from the end and print 1 character
elen=2
echo ${name:0:len} # Prints first 2 characters (note use of len not $len)
Jaecho ${cake:-death} # Outputs $cake or the text death
deathcake="cakes"
echo ${cake:-death}
cakesMoving on slightly to path maniplulation.
fName=/path/to/my/file.name
echo ${fName%.name} # Removes suffix .name
/path/to/my/fileecho ${fName#/path} # Removes prefix /path
/to/my/file.nameecho ${fName%.name}.type # Removes .name and replaces with .type
/path/to/my/file.typeecho ${fName##*.} # Prints the files extension
nameecho ${fName##*/} # Prints filename and extension, equivilent to basename
file.nameecho ${fName#*/} # Removes initial /
path/to/my/file.nameecho ${fName##*/} # Filename and extension
file.nameecho ${fName/a/A} # Replace first occurance of a with A
/pAth/to/my/file.nameecho ${fName//a/A} # Replace all occurances of a with A
/pAth/to/my/file.nAmeecho ${fName/%name/NAME} # Replace suffix
/path/to/my/file.NAMEecho ${#fName} # Print the length
21a1=test
a3=${a2-$a1} # a3 = $a2 or $a1 if $a2 not set
a4=${a2-"this is a test"} # a3 = $a2 or "this is a test" if $a2 not set
echo "a1=$a1 : a2=$a2 : a3=$a3 : a4=$a4"
a1=test : a2= : a3=test : a4=this is a testecho ${a5:=$a1} # Set a5 to $a1 if not set
testecho ${a1:+$a4} # Prints $a4 id $a1 is set
this is a testecho ${a2:?value is not set} # Prints error message is a2 not set
bash: a2: value is not set: '
This is how
you print a
multi line
comment
'