Bash Examples: String Operations

Bash Examples: String Operations

Last updated:
Table of Contents

String matches regex

To check whether a string matches a regular expression use =~ followed by the regex, within double square brackets

Example: string starts with 'f'

if [[ "foo" =~ ^f ]]; then
 echo "match"
fi

String equality

To check if one string is equal to another string use == within double square brackets

if [[ "abc" == "abc" ]]; then
    echo "equal"
else
    echo "not equal"
fi

String contains substring

Use the following: haystack =~ needle within double square brackets

if [[ "foobar" =~ "foo" ]];  then
    echo "contains"
else
    echo "doesn't contain"
fi

Multiline string

variables in the body will not be expanded

A multiline string is called a heredoc.

my_var=$(cat <<'EOF'
foo bar
more text
EOF
)

echo "$my_var"
# foo bar
# more text

Multiline string, with variable expansion

If you use a heredoc delimiter (in this case EOF) without quotes around it, variables will be expanded in the text body:

var1="Hi! I'm var1"

my_var=$(cat <<EOF
foo bar
$var1
more text
EOF
)

echo "$my_var"
# foo bar
# Hi! I'm var1
# more text

Assign heredoc to variable

See above Multiline string

Write heredoc to file

Writing multi-line strings to a file called my_file.txt

cat > "my_file.txt" << 'EOF'
text
more text
EOF

Troubleshooting: here-document at line x delimited by end-of-file (wanted `EOF\')

Make sure there are no extra characters (not even whitespace) after the EOF marker in heredocs