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
- A shell script starts with a shebang (
#!) followed by the path to the shell. - Shell scripts must have executable permissions to run.
Practical Exercise
- Create a shell script named
hello.shwith the above content. - Make it executable using
chmod +x hello.shand 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
- The
ifconstruct tests conditions using test commands ([...]). - Conditions return true or false.
Practical Exercise
- 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
forloop is one of the most common loops in shell scripting.- Loops iterate over lists, arrays, or sequences.
Practical Exercise
- 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
$#gives the total number of supplied arguments.$0refers to the script’s name itself.
Practical Exercise
- 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
- Command outputs can be captured using
$(...). - This allows further processing or display within the script.
Practical Exercise
- Create a script that checks if a directory exists. If it does, list its contents; if not, display an error.