In Bash scripting, variables are used to store and manipulate data. Understanding data types and proper variable usage is fundamental to writing effective scripts.
Variables in Bash are created without explicit data types. Follow these conventions:
# Variable declaration and assignment
variable_name="value"
user_name
). To access the value of a variable, prefix it with a $
symbol:
echo $variable_name
Bash primarily supports three data types: strings, integers, and arrays.
Strings are sequences of characters. Use single or double quotes for string assignment:
name='John'
greeting="Hello, $name!"
Bash treats all variables as strings by default. To perform arithmetic operations, use the (( ))
construct:
num1=5
num2=3
result=$((num1 + num2))
echo "Sum: $result"
Arrays store multiple values under a single variable. Declare an array using parentheses:
fruits=("Apple" "Banana" "Orange")
# Accessing array elements
echo "First fruit: ${fruits[0]}"
Bash provides special variables for various purposes:
$0
: Script name $1
, $2
, ...: Positional parameters $#
: Number of parameters $@
: All positional parameters $?
: Exit status of the last command
# Basic variable usage
name="Alice"
echo "Hello, $name!"
# Arithmetic operations
num1=8
num2=4
result=$((num1 / num2))
echo "Result: $result"
# Array example
colors=("Red" "Green" "Blue")
# Loop through array elements
for color in "${colors[@]}"; do
echo "Color: $color"
done
Continue to Part 4: Control Structures.
Go back to Bash Scripting Guide.
Visit other Developer Guides.