Bash reference
5 November 2023 (Updated 5 November 2023)
String manipulation
Replace string occurrences
Syntax:
${string//substring/replacement}
Example
original_string="Foo bar foo bar foo"
replaced_string=${original_string//foo/***}
echo "$replaced_string"
Variables
Check if string is not set or empty
if [ -z "$variable" ]; then
echo "The variable is empty"
fi
Check if string is non-empty
if [ -n "$variable" ]; then
echo "The variable is not empty"
fi
Arrays
Initialise array
array=(
element1
element2
element3
)
Initialise associate array / dictionary
declare -A assoc_array
assoc_array[key1]=value1
assoc_array[key2]=value2
Append to array
array+=("newElement1")
array+=("newElement2")
Assign value to index
array[0]="element1"
array[1]="element2"
array[2]="element3"
Loop array
for name in "${names[@]}"; do
do
echo "Hello, $name!"
done
Scripts
Check if argument was passed to script
if [ -z "$1" ]; then
echo "No first argument was passed."
else
echo "The first argument is: $1"
fi
Tagged:
Bash
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment