Shell Scripting

Shell Scripting #

Shell scripting is a powerful way to automate tasks, chain commands, and create custom tools on Unix/Linux systems. In this section, I will ll cover the basics of shell scripting using Bash.

Creating a shell script #

To create a shell script, simply create a new file with a .sh extension. The first line of the script should specify the interpreter that will execute the script, in this case /bin/bash. This is known as the shebang and is written as #!/bin/bash.

Here is an example of a complete, simple hello.sh script:

#!/bin/bash

echo "Hello, $(whoami)!"    # Greets the current user

This script will output a personalized greeting by using the echo command and the whoami command enclosed in $(...), which is used for command substitution. Command substitution allows you to use the output of a command within another command or as a string.

Making the script executable #

Before you can run the script, you need to make it executable. Use the chmod command seen previously to make it executable for everyone:

chmod +x hello.sh

Running the script #

To run the script, make sure that you are in the directory containing the script and type:

./hello.sh

This will execute the script and display the personalized greeting.

Hello, ubuntu!

Useful Shell Scripting Constructs #

Here are some basic constructs that can be helpful when writing shell scripts.

Variables #

You can use variables in shell scripts to store values.

#!/bin/bash

name="John Doe"
echo "Hello, $name!"

Special Shell Variables #

Some special variables provide useful information about the script’s execution or the environment. Two of these special variables are $? and $#.

$? is used to obtain the exit status of the most recently executed command. It returns 0 if the command was successful, and a non-zero value if the command failed. This can be helpful to determine whether a command executed successfully or encountered an error, and act accordingly.

#!/bin/bash

# Run a command
ls /nonexistent_directory

# Check the exit status of the ls command
if [ $? -eq 0 ]; then
    echo "Command succeeded"
else
    echo "Command failed"
fi

$# is used to obtain the number of arguments passed to the script or a function. This can be useful when validating the number of arguments provided by the user or when iterating through them.

#!/bin/bash

# Check if the script received exactly two arguments
if [ $# -eq 2 ]; then
    echo "You provided two arguments: $1 and $2"
else
    echo "Error: Please provide exactly two arguments."
fi

These special variables, along with others, can be helpful in creating more robust and error-tolerant shell scripts. They provide a way to check the success of commands and manage input from the user.

Interactivity #

Interactive shell scripts are a great way to create tools that interact with the user by prompting them for input. One such way to accept user input in a Bash script is by using the read command. This command reads a line from the standard input and assigns it to a variable.

Here’s an example of an interactive shell script that asks the user for their name and age and then displays a personalized message:

script

Let’s run it:

run-script

Conditionals #

Use if, elif, and else to create conditional statements.

#!/bin/bash

number=5

if [ $number -eq 5 ]; then
    echo "The number is 5."
elif [ $number -lt 5 ]; then
    echo "The number is less than 5."
else
    echo "The number is greater than 5."
fi

Loops #

Use for and while loops to perform repetitive tasks.

#!/bin/bash

# For loop
for i in {1..5}; do
    echo "This is iteration $i"
done

# While loop
count=1
while [ $count -le 5 ]; do
    echo "This is iteration $count"
    count=$((count + 1))
done

This is just the beginning of what you can do with shell scripting in Bash. As you learn more about Bash and its features, you’ll be able to create more complex and powerful scripts to automate tasks and simplify your workflow.

Practical Backup Script Example #

Let’s use everything. In this example, we have an interactive shell script that takes a source directory and a backup directory from the user, then backs up the source directory to the backup directory while preserving the file structure and adding a timestamp to the backup folder’s name.

backup-script

Running it:

run-backup-script