Bash Strings
Strings in Bash
A string is a piece of text. Bash has built-in ways to change strings, using the ${...} syntax.
Example: Create and Join Strings
Save this as join.sh:
#!/bin/bash
first="Hello"
second="World"
greeting="$first, $second!"
echo $greeting
Run it:
./join.sh
Hello, World!
String Length
Use ${#variable} to get the number of characters:
Example: Get the Length
Save this as length.sh:
#!/bin/bash
text="Bash"
echo ${#text}
Run it:
./length.sh
4
Substrings
Use ${variable:start:length} to get part of a string. The first character is at position 0:
Example: Get Part of a String
Save this as sub.sh:
#!/bin/bash
text="Hello World"
echo ${text:0:5}
echo ${text:6}
Run it:
./sub.sh
Hello
World
If you leave out the length, you get everything from the start position to the end.
Replace Text
Use ${variable/old/new} to replace the first match, and ${variable//old/new} to replace all matches:
Example: Replace Text
Save this as replace.sh:
#!/bin/bash
text="I like cats. Cats are fun. cats!"
echo ${text/cats/dogs}
echo ${text//cats/dogs}
Run it:
./replace.sh
I like dogs. Cats are fun. cats!
I like dogs. Cats are fun. dogs!
Note that "Cats" with a capital C did not change, because the match is case-sensitive.
Remove a Prefix or Suffix
Use # to remove a pattern from the start, and % to remove a pattern from the end. This is very useful for file names:
Example: Remove Start and End
Save this as trim.sh:
#!/bin/bash
file="report.final.txt"
echo ${file%.txt}
echo ${file%%.*}
echo ${file#*.}
Run it:
./trim.sh
report.final
report
final.txt
%removes the shortest match from the end,%%the longest#removes the shortest match from the start,##the longest
Upper and Lower Case
Use ^^ to make the string upper case, and ,, to make it lower case:
Example: Change Case
Save this as case.sh:
#!/bin/bash
name="Bash Scripting"
echo ${name^^}
echo ${name,,}
Run it:
./case.sh
BASH SCRIPTING
bash scripting
Compare Strings
Use == and != inside [[ ]] to compare strings, and -z to check if a string is empty:
Example: Compare Strings
Save this as compare.sh:
#!/bin/bash
a="apple"
b="banana"
if [[ $a == $b ]]; then
echo "Same"
else
echo "Different"
fi
empty=""
if [[ -z $empty ]]; then
echo "The string is empty"
fi
Run it:
./compare.sh
Different
The string is empty