Bash: Variables
Variables are used to store data, like text or numbers, that you can use later in your script.
Defining Variables
Basic variable definition
my_string="Hello World"To define a variable, use `name="value"`. Note that there should be no spaces around the equals sign.
Integer and floating-point variables
my_integer=10
my_float=10.5 Numbers can be assigned directly without quotes. Bash treats all variables as strings by default, but you can perform arithmetic operations on integers using `((...))`.
Accessing and Printing Variables
Accessing a variable
echo $my_stringTo 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.
Exporting 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.
Arithmetic Operations
Performing arithmetic with variables
a=5
b=3
sum=$((a + b))
echo "Sum: $sum" You can perform arithmetic operations using the $((...)) syntax. Bash supports addition +, subtraction -, multiplication *, division /, and more for integer variables.
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.