Bash Scripting Basics
What is Bash Scripting?
Bash (Bourne-Again SHell) is a popular command-line shell and scripting language used in Linux and other Unix-like operating systems. Bash scripting allows you to automate repetitive tasks, streamline workflows, and write powerful shell scripts to enhance your productivity.
Basic Bash Syntax
Bash scripts typically have a .sh
file extension and start with the shebang #!/bin/bash
to specify the interpreter. Bash scripts can contain variables, functions, control structures (e.g., if-else
, for
, while
), and various built-in commands.
#!/bin/bash
## Declare a variable
MY_VAR="Hello, LabEx!"
## Print the variable
echo $MY_VAR
Bash supports both local and environment variables. You can assign values to variables using the =
operator and access them using the $
prefix.
## Declare a variable
MY_NAME="LabEx"
## Get user input
read -p "What is your name? " USER_NAME
echo "Hello, $USER_NAME!"
Bash Control Structures
Bash provides various control structures to create conditional logic and loops in your scripts.
## If-else statement
if [ "$MY_NAME" == "LabEx" ]; then
echo "Welcome, LabEx!"
else
echo "Sorry, you are not LabEx."
fi
## For loop
for i in 1 2 3; do
echo "Iteration $i"
done
Bash Functions
You can define and call custom functions in your Bash scripts to encapsulate reusable logic.
## Define a function
greet() {
echo "Hello, $1!"
}
## Call the function
greet "LabEx"
Bash Scripting Best Practices
- Use meaningful variable and function names
- Add comments to explain the purpose of your script
- Handle user input and error cases
- Make your scripts portable by using the
#!/bin/bash
shebang
- Test your scripts thoroughly before using them in production
By understanding these Bash scripting basics, you'll be well on your way to leveraging the power of Bash in your daily workflows and Docker builds.