Bash Scripting: Basics
Bash Scripting: Basics
Bash scripting is the process of writing shell scripts that automate tasks in a Linux or Unix environment. Bash is a popular shell used on Linux and Unix systems, and is the default shell on most Linux distributions.
Creating a Bash Script
To create a Bash script, you'll need to open a text editor and start writing your script. You can create a Bash script by following these steps:
- Open a text editor such as nano, vim, or gedit.
- Type the shebang line, which tells the system which interpreter to use to execute the script. The shebang line for Bash scripts is
#!/bin/bash
. - Add your script commands below the shebang line.
- Save the file with a
.sh
extension.
Here's an example of a simple Bash script that prints "Hello World!" to the terminal:
Running a Bash Script
To run a Bash script, you'll need to make it executable first. You can do this by using the chmod
command:
chmod +x script.sh
This sets the executable bit on the script file, allowing you to run it as a program. To run the script, simply type its filename:
./script.sh
This will execute the script and output the result to the terminal.
Variables in Bash
Variables in Bash are used to store data that can be used by the script. Bash variables are untyped, which means they can hold any type of data. To create a variable in Bash, you simply assign a value to it:
name="John"
You can then use the variable in your script by referencing its name with the $
symbol:
echo "Hello, $name!"
This will output "Hello, John!" to the terminal.
Command-Line Arguments
Bash scripts can accept command-line arguments, which are values passed to the script when it's executed. Command-line arguments are accessed in the script using special variables:
$0
refers to the script name itself.$1
refers to the first argument.$2
refers to the second argument.- And so on.
Here's an example of a Bash script that accepts two command-line arguments and prints them to the terminal:
You can run this script with the following command:
./script.sh hello world
This will output:
Conclusion
In this section, we covered the basics of Bash scripting, including creating and running scripts, using variables, and accepting command-line arguments. Bash scripting is a powerful tool for automating tasks in a Linux or Unix environment, and can save you time and effort in your daily work.