Bash Scripting is a handy and powerful tool for automating tasks on a Unix-like operating system. It is a command language interpreter that executes commands read from the standard input or from a file. Bash also incorporates useful features from the Korn and C shells (ksh and csh).
Variables
Variables in Bash are used to store data. They can be used to store strings, numbers, and other types of data. Variables are defined using the =
operator.
name="John"
age=25
List and Array
Bash supports lists and arrays. Lists are used to store a sequence of elements, while arrays are used to store a collection of elements.
# List
fruits="apple orange banana"
# Accessing list elements
echo $fruits
# Iterating over list elements
for fruit in $fruits; do
echo $fruit
done
# Array
colors=("red" "green" "blue")
# Accessing array elements
echo ${colors[0]}
# Iterating over array elements
for color in ${colors[@]}; do
echo $color
done
Control Statements
Bash supports various control statements, including if
, case
, for
, while
, and until
. These control statements are used to direct the flow of the program based on conditions.
# If statement
if [ $age -gt 18 ]; then
echo "You are an adult"
else
echo "You are a minor"
fi
# For loop
for i in {1..5}; do
echo $i
done
# While loop
count=0
while [ $count -lt 5 ]; do
echo $count
((count++))
done
Functions
Bash functions allow you to group commands and execute them as a single unit. They are useful for code reuse and modularity.
# Function definition
greet() {
echo "Hello, $1!"
}
# Function call
greet "John"
File Operations
Bash provides a wide range of file operations, including reading, writing, and manipulating files. It also supports file permissions and ownership.
# Read file
cat file.txt
# Write to file
echo "Hello, World!" > file.txt
# Append to file
echo "Hello, World!" >> file.txt
# Read file line by line
while IFS= read -r line; do
echo "$line"
done < file.txt
# File permissions
chmod 755 file.sh
Advanced Features
[[ ]]
is a more powerful version of [ ]
and is used for conditional expressions. It supports pattern matching and regular expressions.
# Conditional expression
if [[ $age -gt 18 && $age -lt 60 ]]; then
echo "You are eligible to work"
fi
$()
is used to execute commands and capture their output. It is similar to backticks but is more readable and easier to nest.
# Command substitution
files=$(ls)
echo $files
$?
is a special variable that holds the exit status of the last command. It is used to check the success or failure of a command.
# Check exit status
ls
echo $?
$@
and $*
are used to access all the command-line arguments passed to a script or function.
# Command-line arguments
echo $@ // prints all arguments
echo $* // prints all arguments as a single string