Bash scripting is a powerful tool for automating tasks, managing systems, and creating efficient workflows in Linux. This chapter introduces the fundamentals of Bash scripting, common use cases, and advanced techniques to write robust scripts.
- A Bash script is a file containing a series of commands that are executed sequentially by the Bash shell.
- Scripts are used to automate repetitive tasks and manage system operations.
- Open a text editor (e.g.,
nano
,vim
). - Write your script.
- Save the file with a
.sh
extension (e.g.,script.sh
). - Make the script executable using
chmod
:chmod +x script.sh
- Run the script:
./script.sh
#!/bin/bash
# Simple Bash Script
echo "Hello, World!"
- The shebang specifies the interpreter for the script.
- Common example:
#!/bin/bash
- Use
#
for single-line comments. - Use comments to document the purpose of your script and its sections.
- Store and reuse data within the script.
VARIABLE_NAME=value
name="Linux User"
echo "Hello, $name!"
if [ condition ]; then
# Commands
else
# Commands
fi
#!/bin/bash
number=10
if [ $number -gt 5 ]; then
echo "Number is greater than 5"
else
echo "Number is 5 or less"
fi
for var in list; do
# Commands
done
for i in 1 2 3 4 5; do
echo "Number: $i"
done
while [ condition ]; do
# Commands
done
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
- Functions allow you to organize reusable blocks of code.
function_name() {
# Commands
}
#!/bin/bash
hello() {
echo "Hello, $1!"
}
hello "World"
- Use
read
to get input from the user.
#!/bin/bash
echo "Enter your name:"
read name
echo "Hello, $name!"
- Redirect standard output to a file:
command > file
- Append output to a file:
command >> file
- Redirect standard error:
command 2> error.log
- Use
-x
to debug a script:bash -x script.sh
- Use
set -x
to enable debug mode within a script andset +x
to disable it.
#!/bin/bash
set -x
echo "Debugging this script"
set +x
echo "Debugging disabled"
- Store multiple values in a single variable.
fruits=("apple" "banana" "cherry")
echo ${fruits[1]}
- Handle multiple conditions elegantly.
#!/bin/bash
echo "Enter a number:"
read number
case $number in
1)
echo "You entered one" ;;
2)
echo "You entered two" ;;
*)
echo "Invalid choice" ;;
esac
By the end of this chapter, you should be able to:
- Write and execute basic Bash scripts.
- Use variables, control structures, and functions in scripts.
- Handle user input and output effectively.
- Debug scripts and implement advanced scripting techniques.
- Move to Chapter 9: Compressing and Archiving to learn about managing file compression and archives in Linux.
- Write a script that calculates the factorial of a number using a
while
loop. - Create a script that backs up a directory to a specified location.
- Write a script to check if a file exists and display an appropriate message.
- Use a
for
loop to iterate through all.txt
files in a directory and display their content. - Debug a script using
bash -x
and identify potential issues.