This tutorial will guide you through the basic concepts of BASH shell scripting. It will include creating, writing, and executing scripts.
Step 1: Introduction to BASH
BASH (Bourne Again Shell) is a shell program in Unix. It's a command processor that allows you to type commands and get results.
Practice Exercise
Show Solution
Step 2: Creating a BASH Script
Let's start by creating a simple BASH script. In Unix, scripts start with a 'shebang' (#!) followed by the path to the interpreter.
#!/bin/bashPractice Exercise
Create a new BASH script file named 'myscript.sh'.
Show Solution
Use the 'touch' command to create a new file: touch myscript.shStep 3: Writing a BASH Script
Now that we have our script file, we can write our first script. Let's print 'Hello, World!' to the console.
#!/bin/bash
echo 'Hello, World!'Practice Exercise
Edit 'myscript.sh' to print 'Hello, World!' to the console.
Show Solution
Use a text editor to add the following line to 'myscript.sh': echo 'Hello, World!'Step 4: Executing a BASH Script
To run our script, we first need to make it executable with the 'chmod' command. Then, we can run it using the './' prefix.
chmod +x myscript.sh
./myscript.shPractice Exercise
Make 'myscript.sh' executable and run it.
Show Solution
Use the following commands: chmod +x myscript.sh; ./myscript.shStep 5: Using Variables in BASH Scripts
Variables allow us to store and manipulate data in our scripts. They are declared with the '=' operator and accessed with the '$' prefix.
name='John'
echo "Hello, $name!"Practice Exercise
Create a variable 'name' in 'myscript.sh' and print a greeting message using this variable.
Show Solution
Add the following lines to 'myscript.sh': name='John'; echo "Hello, $name!"Step 6: Using Conditional Statements in BASH Scripts
Conditional statements allow us to perform different actions based on certain conditions. The 'if' statement is the most common conditional statement in BASH.
if [ $name == 'John' ]; then
echo 'Hello, John!'
else
echo 'Hello, stranger!'
fiPractice Exercise
Modify 'myscript.sh' to print 'Hello, John!' if 'name' is 'John', and 'Hello, stranger!' otherwise.
Show Solution
Add the following lines to 'myscript.sh': if [ $name == 'John' ]; then echo 'Hello, John!'; else echo 'Hello, stranger!'; fiStep 7: Using Loops in BASH Scripts
Loops allow us to execute a block of code multiple times. The 'for' loop is commonly used in BASH scripting.
for i in {1..5}; do
echo $i
donePractice Exercise
Modify 'myscript.sh' to print the numbers from 1 to 5 using a for loop.
Show Solution
Add the following lines to 'myscript.sh': for i in {1..5}; do echo $i; done