Bash Scripting Tutorial – Linux Shell Script and Command Line for Beginners

Bash Scripting Tutorial Banner

Are you new to Linux and interested in learning how to write shell scripts? In this beginner-friendly Bash scripting tutorial, we‘ll cover all the essential concepts you need to know to start automating tasks and working efficiently in the Linux command line interface.

What is Bash Scripting?

Bash (Bourne Again Shell) is the default shell environment in most Linux distributions. A shell script is simply a text file containing a sequence of commands that are executed by the shell.

Bash scripting allows you to automate repetitive tasks, manipulate files, process data, and interact with system resources. Instead of manually typing commands in the terminal, you can save a set of instructions in a script file and execute it anytime.

Some key advantages of Bash scripting:

  • Automation of routine tasks
  • Ability to combine simple commands into powerful programs
  • Easy manipulation of files and data
  • Portability across Unix-like systems
  • Integration with other languages and tools

The Linux Command Line Interface

Before diving into scripting, let‘s briefly review the Linux command line. When you open a terminal window, you‘re presented with a command prompt that looks something like this:

user@host:~$

Here you can enter commands to navigate the filesystem, manipulate files, install software, and much more. For example, some commonly used commands:

  • ls – list files and directories
  • cd – change the current directory
  • mkdir – create a new directory
  • cat – display the contents of a file
  • grep – search for patterns in files

We‘ll be using many of these commands in our Bash scripts, so familiarity with the command line will be very helpful as you learn scripting.

Writing Your First Bash Script

Let‘s create a simple "Hello World" script to demonstrate the process of writing and executing a Bash script:

  1. Open a text editor and create a new file named hello.sh
  2. Add the following lines to the file:
#!/bin/bash
echo "Hello World!"
  1. Save the file and exit the editor.
  2. Make the script executable with the command:

chmod +x hello.sh

  1. Run the script:

./hello.sh

You should see the output "Hello World!" printed in the terminal. Let‘s break down the key parts:

  • The first line #!/bin/bash is known as the "shebang". It specifies the interpreter that should be used to run the script, in this case Bash.
  • echo is a command that prints text to the screen. You can use it to output messages, variables, or command output.

With this basic template, you can start building more complex scripts by adding variables, control structures, and additional commands. But first, let‘s look at some core scripting concepts.

Variables and User Input

Variables allow you to store and manipulate data within your Bash scripts. To declare a variable, simply use the syntax:

name="John"

And to access its value, use the $ symbol:

echo "Hello $name"

Bash variables are untyped, meaning you can store numbers, strings, or other data without specifying a type. However, there are some special variables that have predefined meanings, such as:

  • $0 – the name of the script
  • $1, $2, ... – the positional parameters passed to the script
  • $# – the number of arguments passed
  • $? – the exit status of the last executed command

To get input from the user, you can use the read command:

echo "What is your name?"
read name 
echo "Hello $name"

This will prompt the user to enter their name and store it in the variable name.

Conditional Statements

Bash supports standard conditional statements like if/else and case. The basic syntax for an if statement is:

if [[ condition ]]; then
  # commands
elif [[ condition ]]; then
  # commands  
else
  # commands
fi

The condition can be any valid Bash expression that evaluates to either true or false. Some common operators:

  • -eq – equal to
  • -ne – not equal to
  • -lt – less than
  • -gt – greater than
  • = – string equal to
  • != – string not equal to

For example, a script that checks if a number is positive or negative:

echo "Enter a number"  
read num

if [[ $num -gt 0 ]]; then echo "Positive" elif [[ $num -lt 0 ]]; then
echo "Negative" else echo "Zero"
fi

The case statement is used to match a variable against multiple patterns, similar to a switch statement in other languages:

echo "Enter a fruit"
read fruit

case $fruit in apple) echo "You chose an apple" ;; banana) echo "You chose a banana" ;; *)
echo "Unknown fruit" ;; esac

The *) pattern is a catch-all that matches any value not listed.

Loops

Bash provides three types of loops: for, while, and until. The for loop iterates over a list of values:

for i in 1 2 3; do
  echo $i
done  

This will output the numbers 1, 2, and 3. You can also iterate over the contents of a variable, the output of a command, or a range of numbers:

  
files=$(ls)
for file in $files; do
  echo $file  
done

The while loop continues as long as its condition is true:

count=1
while [[ $count -le 5 ]]; do
  echo $count
  count=$((count + 1))
done  

This will print the numbers 1 through 5.

The until loop is similar to while, but it continues as long as its condition is false:

  
count=1
until [[ $count -gt 5 ]]; do
  echo $count
  count=$((count + 1))  
done

Again, this will print the numbers 1 through 5.

Functions

Functions allow you to encapsulate a set of commands that can be called multiple times within your script. The syntax to define a function is:

function_name() {
  # commands
}  

And to call it:

  
function_name

Functions can take arguments and return values just like in other programming languages. For example:

greet() {
  echo "Hello $1"
}

greet "John" greet "Mary"

This will output:

  
Hello John
Hello Mary

Functions are useful for breaking down your script into logical, reusable parts and make your code more readable and maintainable.

Debugging

As your Bash scripts get more complex, you‘ll inevitably run into bugs or unexpected behavior. Here are some tips for debugging your scripts:

  • Add set -x at the beginning of your script to enable trace mode, which will print each command as it is executed.
  • Use echo statements liberally to print out variable values and see how far your script gets before an error.
  • Check the exit status of commands with $? to see if they completed successfully.
  • Validate your script‘s syntax with bash -n script.sh before running it.

With practice, you‘ll develop an intuition for tracking down issues in your scripts.

Scheduling Scripts

Once you‘ve written a useful Bash script, you may want to schedule it to run automatically at certain times. This is where cron comes in.

Cron is a job scheduler that allows you to specify commands to be run at regular intervals. It reads configuration files known as crontabs that define the schedule for each job.

To edit your user‘s crontab, run:

crontab -e

This will open the crontab file in your default text editor. Each line represents a separate job in the format:

* command

The asterisks represent the minute, hour, day of month, month, and day of week fields respectively. For example, to run a script every day at midnight:

0 0 * /path/to/script.sh

Save the file and exit the editor to install the new crontab. Your script will now run automatically according to the schedule you specified.

You can view your active crontab with crontab -l and remove it entirely with crontab -r.

Conclusion

We‘ve covered a lot of ground in this tutorial, from the basics of the Bash shell and command line to writing scripts with variables, conditionals, loops, and functions. We also touched on more advanced topics like debugging and scheduling scripts with cron.

Remember, the best way to learn Bash scripting is through practice. Start small, experiment in the shell, and gradually build up to more complex scripts that automate your common tasks.

Here are some resources to continue your learning:

I hope this tutorial has given you a solid foundation in Bash scripting and sparked your interest in exploring the power of the Linux command line further. Happy scripting!

Similar Posts