Bash: String Variables
String variables are used to store and manipulate text in Bash scripts.
Defining String Variables
Basic variable definition
my_string="Hello World" To define a string variable, use name="value". Note that there should be no spaces around the equals sign.
Accessing and Printing String Variables
Accessing a variable
echo $my_string To use the value stored in a variable, precede its name with a dollar sign $. The echo command prints the value to the terminal.
Concatenating Strings
Combining variables and strings
full_name="John Doe" echo "My name is $full_name"Bash automatically concatenates adjacent strings and variables. You can combine multiple variables or mix them with regular text inside double quotes.
Getting Length of a String
Find the length of a string variable
my_string="Hello World"
echo ${#my_string} To get the length of a string stored in a variable, use ${#variable_name}. This returns the number of characters in the string.
Splitting a String into an Array
Splitting a string by a delimiter
my_string="apple,banana,cherry"
IFS=',' read -ra fruits <<< "$my_string"
echo "${fruits[0]}" # apple
echo "${fruits[1]}" # banana To split a string into an array, set the IFS (Internal Field Separator) to your delimiter and use read -ra to assign the words read to sequential indices of the array fruits.
Exporting String Variables
The export keyword
export my_variable="Some Value" The export keyword makes a variable available to child processes or scripts. Without export, a variable is only available in the current shell session.