About
String Variable, see also character
string in bash.
Initialization
Function Arg
When calling a function, quote the variable otherwise bash will not see the string as atomic but as an array
output_args()
{
for arg
do
echo "$arg"
done
}
var="hello Nico"
echo "Without Quotes"
echo "**************"
output_args $var
echo
echo "With Quotes"
echo "**************"
output_args "$var"
Without Quotes
**************
hello
Nico
With Quotes
**************
hello Nico
Initialization from File
- Sh with Bash - Back-tick
#!/bin/sh
echo 'hello' > hello.txt
test=`cat hello.txt `
echo $test
hello
- Bash
#!/bin/bash
value=$(<file.txt)
echo "$value"
Quote
Double Quote - $“string”
double quotes 1) (“) preserves the literal value of all characters within the quotes.
The default for a string variable
var="My
string"
echo "$var" # The space and eol are preserved
#vs
echo $var # Double space and eol are deleted
A double-quoted string preceded by a dollar sign $”string“ will cause the string to be translated according to the current locale.
If the current locale is C or POSIX, the dollar sign is ignored.
If the string is translated and replaced, the replacement is double-quoted.
Single Quote - $'string'
From the bash man page, words of the form $'string' are treated specially.
The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.
The expanded result is single-quoted, as if the dollar sign had not been present.
EOL Bash
The below code will produce:
var=$'Hello\nWorld'
echo $var
Hello
World
EOL Posix compliant
BAR=$(printf "hello\nworld\n")
Escape
The escape character is a backslash \
Function
Concatenation
Write the variable one after another:
- Concatenation without space:
var1=Hello
var2=Nico
echo $var1$var2
HelloNico
var1=Hello
var2=Nico
echo $var1 $var2
Hello Nico
- concatenation with space
var3="${var1} ${var2}"
echo $var3
Hello Nico
- Concat with the += assignment operator. value is expanded and appended to the variable’s value.
MY_VARIABLE=A
MY_VARIABLE+=B
echo $MY_VARIABLE
AB
- Concat backslash character
variable="First"$'\n'
variable=$variable"Second"$'\n'
echo "$variable"
First
Second
Split
- Cut: Split on a line level
echo -e 'One,Two,Three,Four\nOne,Two,Three,Four' | cut -d ',' -f 1-2,4 --output-delimiter=' '
One Two Four
One Two Four
Substring
- With substring_expansion, you can get a part of the string.
Example:
UNKNOWN=unknown
echo ${UNKNOWN:2:3}
kno
- The last 3 digits
echo ${UNKNOWN: -3} # the space is important, get the
- or with cut
echo "nicolas" | cut -c1-4
nico
- Last three character
echo -n "nicolas" | tail -c 3
- From to (from 2 to -2) - rev reverse the string
echo -n "nicolas" | cut -c2- | rev | cut -c2- | rev
icola
Remove a part
With Parameter Expansion Removal operation, you can remove a part of the string.
MY_VARIABLE=123
echo ${MY_VARIABLE#1}
23
See also:
- Shell Data Processing - tr (translate or delete characters) to delete a class of characters
- tail -n +2 to suppress the first line
Length
With length parameter expansion, you can get the length of a string variable.
MY_VARIABLE=123
echo ${#MY_VARIABLE}
3
Uppercase / Lowercase / InitCap / CamelCase
- Before bash 4:
# From upper to lower
echo "HELLO WORLD" | tr '[:upper:]' '[:lower:]'
# With a variable
X=$(echo "${X}" | tr '[:upper:]' '[:lower:]')
- With Bash 4:
hello="HELLO WORLD"
echo ${hello,,} # Lowercase
echo ${hello,} # Lowercase First letter
echo ${hello^^} # Uppercase
echo ${hello^} # Uppercase First letter
Replace
Bash parameters expansion
Replacement with parameter expansion ?
- Replace first match of substring with replacement.
${string/substring/replacement}
# Replacing all / in a path
foo=`pwd`
echo ${foo////_}
- Replace all matches of substring with replacement.
${string//substring/replacement}
- If substring matches front end of string, substitute replacement for substring.
${string/#substring/replacement}
- If substring matches back end of string, substitute $replacement for substring.
${string/%substring/replacement}
- The Escape character is the \ backslash
word="hello/nico"
# Replacing the / character with a space
echo ${word//\// }
hello nico
Others
See also:
Extract
- With built-in regexp operator, See How to use Regular expression (regex) in Bash?
regexp=$'[^ ]*\s(.*)' # Mandatory to put the regexp in a variable
if [[ "Hello Nico" =~ $regexp ]]; then echo "Match : First group is (${BASH_REMATCH[1]})"; else echo "No match"; fi;
Match : First group is (Nico)
to Array
IFS=', ' read -r -a array <<< "$string"
example
IFS=',' read -r -a myArray <<< "hello,nico"
echo ${#myArray[*]} # length of 2
echo ${myArray[*]}
hello nico
Comparison
Name | Double Bracket operator | Single Bracket Operator | Example |
---|---|---|---|
Greater than | > | \> (*) | [[ a > b ]] || echo "a does not come after b" |
Lower than | < | \< (*) | [[ az < za ]] && echo "az comes before za" |
Equality | = (or ==) | = | [[ a = a ]] && echo "a equals a" |
Not Equal | != | != | [[ a != b ]] && echo "a is not equal to b" |
Pattern matching | = (or ==) | (not available) | [[ $name = a* ]] || echo "name does not start with an 'a': $name" |
RegularExpression matching | =~ | (not available) | [[ $(date) =~ ^Fri\ ...\ 13 ]] && echo "It's Friday the 13th!" |
Comparison Operator
Comparison operator in bash conditional expression for strings.
- = : is equal to. With the whitespace framing the = equals char.
if [ "$a" = "$b" ]
# is not the same than (Why???)
if [ "$a"="$b" ]
- == is equal to.
if [ "$a" == "$b" ] # Synonym of ''=''
[[ $a == z* ]] # True if $a starts with a "z" (pattern matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
[ $a == z* ] # File globbing and word splitting take place.
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).
- < is less than, in ASCII alphabetical order
if [[ "$a" < "$b" ]]
if [ "$a" \< "$b" ] # The "<" char needs to be escaped in a [ construct
- != is not equal to. Pattern matching within a [[ ... ]] construct.
if [ "$a" != "$b" ]
- -z string has zero length
- -n string is not null
Example:
Quote strings within test brackets as the variable may be not initialized
if [ -n "$string1" ]
then
echo "String \"string1\" is not null."
else
echo "String \"string1\" is null."
fi
- You can also use the named comparison operators (demo is for integer but they works also for string)
Double Bracket operator | Single Bracket Operator | Example |
---|---|---|
-lt | -lt | [[ 8 -lt 9 ]] && echo "8 is less than 9" |
-ge | -ge | [[ 3 -ge 3 ]] && echo "3 is greater than or equal to 3" |
-gt | -gt | [[ 5 -gt 10 ]] || echo "5 is greater than than 10" |
-le | -le | [[ 3 -le 8 ]] && echo "3 is less than or equal to 8" |
-eq | -eq | [[ 5 -eq 05 ]] && echo "5 equals 05" |
-ne | -ne | [[ 6 -ne 20 ]] && echo "6 is not equal to 20" |
Contains
See equality operator above with the [[ ... ]] construct.
Example:
if [[ ! "${DIRECTORY_TO_CLEAN}" =~ ^(/opt/infa/|/home/).* ]] ; then
echo_err "Directory To Clean parameter must be a directory inside /opt/infa or /home/"
close_script 1
fi
Documentation / Reference
- bash man page