Lesson 1, Topic 1
In Progress

Creating Simple Shell Scripts

1. Introduction to Shell Scripting

Shell scripting is the act of creating and writing shell scripts. A shell script is a series of command-line instructions written in plain text and executed by the shell.

Example:

#!/bin/bash
echo "Hello, World!"

Summary

  • Shell scripting enables automation and simplification of routine tasks.

Key Points

  1. A shell script starts with a shebang (#!) followed by the path to the shell.
  2. Shell scripts must have executable permissions to run.

Practical Exercise

  1. Create a shell script named hello.sh with the above content.
  2. Make it executable using chmod +x hello.sh and run it with ./hello.sh.

2. Conditionally Executing Code

Conditional execution allows code to run based on a condition.

Example:

#!/bin/bash
if [ "$1" == "RHCSA" ]; then
  echo "Welcome to RHCSA study guide!"
else
  echo "Welcome, user!"
fi


Summary

  • Using conditions, scripts can be made more dynamic.

Key Points

  1. The if construct tests conditions using test commands ([...]).
  2. Conditions return true or false.

Practical Exercise

  1. Modify the script to greet the user by name if provided as an argument.

3. Looping Constructs in Scripts

Looping allows for repetitive execution of code.

Example:

#!/bin/bash
for i in {1..5}; do
  echo "Iteration number $i"
done


Summary

  • Loops can be used to execute a block of code multiple times.

Key Points

  1. for loop is one of the most common loops in shell scripting.
  2. Loops iterate over lists, arrays, or sequences.

Practical Exercise

  1. Create a script that takes filenames as arguments and displays the contents of each file.

4. Processing Script Inputs

Shell scripts can take arguments that are referenced as $1, $2, etc.

Example:

#!/bin/bash
echo "The first argument is: $1"
echo "The second argument is: $2"


Summary

  • Script inputs allow scripts to be versatile.

Key Points

  1. $# gives the total number of supplied arguments.
  2. $0 refers to the script’s name itself.

Practical Exercise

  1. Create a script that sums up three numbers provided as arguments.

5. Processing Output of Shell Commands within a Script

Shell commands can be executed within a script, and their outputs can be stored in variables.

Example:

#!/bin/bash
output=$(ls)
echo "The contents of the current directory are: $output"


Summary

  • Storing command outputs is beneficial for dynamic operations.

Key Points

  1. Command outputs can be captured using $(...).
  2. This allows further processing or display within the script.

Practical Exercise

  1. Create a script that checks if a directory exists. If it does, list its contents; if not, display an error.