Bash scripting is a collection of Linux commands organized to perform some task. Is like a programming language, but instead is a scripting language because it it based on bash commands and not a really native programming language.
Bash scripts are plain text files with a .sh extension. You can create a new file using your favorite text editor, like nano or vim. All the bash scripts have to have on the first line the following text:
#!/bin/bash
The previous line declares the file as a bash script by explicitly defining /bin/bash as the run command. In order to run a bash script the file must be executable and for that you have to set it with the following command:
chmod +x script_name.sh
Any Linux command can be set on a bash script, The most basic one is the echo that permits to echo a message to the screen. Variables can also be declared as well as throwing data into the script when calling it to run.
Here is a simple example of a Bash script that prints “Hello, World!” to the terminal:
#!/bin/bash
echo "Hello, World!"
To set a variable use the equal operator like this:
MY_VAR="Hello, World!"
Then use it by referencing its name with a dollar character. Here is an example with an if statement that uses the previously declared variable and then return a customized message:
if [ "$MY_VAR" == "Hello, World!" ]; then
echo "My variable is set correctly."
else
echo "My variable is not set correctly."
fi
Loops are also possible and very useful to write scripts. Here is an example of a for loop:
for i in $(seq 1 10); do
echo "Iteration $i"
done
Execute the script with two parameters like the following example:
./script_name.sh foo bar
Now catch those parameters and set them as variables:
#!/bin/bash
# Catching the first argument
arg1=$1
echo "The first argument is: $arg1"
# Catching the second argument
arg2=$2
echo "The second argument is: $arg2"
The final output will be:
The first argument is: foo
The second argument is: bar
Way more can be done with bash scripts, like changing file contents, moving files, trigger alerts, install packages, clean up data and even create games. Just use your imagination and start creating your own bash scripts to see the power of command line automation.
Leave a Reply