Bash Scripting Basics
What is Bash Scripting?
Bash (Bourne-Again SHell) is a popular command-line interface and scripting language used in various Unix-based operating systems, including Linux. Bash scripting allows you to automate repetitive tasks, streamline workflows, and create custom tools to enhance your productivity.
Basic Bash Syntax
Bash scripts are plain text files that contain a series of commands, variables, and control structures. The basic syntax for a Bash script includes:
- Shebang line:
#!/bin/bash
- Comments:
## This is a comment
- Variables:
MY_VARIABLE="value"
- Commands:
echo "Hello, LabEx!"
- Control structures:
if, then, else, fi
Running Bash Scripts
To run a Bash script, you need to make the script executable using the chmod
command:
chmod +x script.sh
Then, you can execute the script using the following command:
./script.sh
Bash supports various types of variables, including string, integer, and array. You can assign values to variables and use them throughout your script. To get user input, you can use the read
command:
echo "What is your name?"
read name
echo "Hello, $name!"
Bash Control Structures
Bash provides several control structures to add logic and decision-making to your scripts, such as if-else
, case
, for
, while
, and until
loops.
if [ "$name" == "LabEx" ]; then
echo "Welcome, LabEx!"
else
echo "Hello, $name!"
fi
Bash Functions
You can create custom functions in your Bash scripts to encapsulate and reuse common tasks.
greet() {
echo "Hello, $1!"
}
greet "LabEx"