String Manipulation
Bash can slice, search, and transform strings without calling out to external tools like sed or awk — through a set of expansions built directly into the shell.
Length and substrings
bash substrings.sh
#!/bin/bash filename="report-final.txt" echo "Length: ${#filename}" echo "First 6 chars: ${filename:0:6}" echo "From position 7: ${filename:7}"
Terminal output
Length: 16 First 6 chars: report From position 7: final.txt
Replacing text
${var/old/new} replaces the first match; ${var//old/new} replaces every match:
bash replace.sh
#!/bin/bash sentence="the cat sat on the mat" echo "${sentence/the/a}" echo "${sentence//the/a}"
Terminal output
a cat sat on the mat a cat sat on a mat
Extracting a file extension
bash extension.sh
#!/bin/bash filename="photo.backup.jpg" extension="${filename##*.}" echo "Extension: $extension"
Terminal output
Extension: jpg
${filename##*.} strips everything up to and including the last ., which is why it correctly returns jpg even though the filename has two dots.
Case conversion
bash case.sh
#!/bin/bash name="Maya" echo "${name^^}" echo "${name,,}"
Terminal output
MAYA maya
Note: everything on this page is a Bash-specific extension, not part of the plain POSIX
sh standard. If a script's shebang is #!/bin/sh instead of #!/bin/bash, none of these expansions are guaranteed to work — keep the shebang as #!/bin/bash if you're relying on them.