Create Shell Script With Inputs

Red Hat Enterprise LinuxBeginner
Practice Now

Introduction

In this challenge, you will learn how to create a simple shell script that can accept and process input parameters. Shell scripts are a powerful tool in the Linux environment, allowing you to automate repetitive tasks and streamline your workflow. By mastering the use of script inputs, you can make your scripts more flexible and dynamic, tailoring them to specific needs. This is a fundamental skill for system administrators and is often tested in certifications like RHCSA.

Create a Shell Script with Input Parameters

In this step, you will create a shell script that accepts two input parameters from the command line. These parameters will then be used within the script to perform a simple arithmetic operation. Understanding how to handle input parameters is crucial for writing flexible and reusable scripts.

Tasks

  • Create a shell script named script.sh in the ~/project directory.
  • The script should accept two numerical input parameters.
  • The script should calculate the sum of these two parameters.
  • The script should print the result of the addition to the standard output.

Requirements

  • The shell script must be named script.sh.
  • The script must be located in the ~/project directory.
  • The script must use the $1 and $2 variables to access the first and second input parameters, respectively.
  • The script must perform an addition operation on the two input parameters.
  • The script's output format must be exactly The result is: <sum>, where <sum> is the calculated sum.

Example

Here's an example of how your script should behave when executed:

[labex@host ~]$ mkdir -p ~/project
[labex@host ~]$ cd ~/project
[labex@host project]$ nano script.sh
## (After creating and saving the script)
[labex@host project]$ chmod +x script.sh
[labex@host project]$ ./script.sh 10 20
The result is: 30
[labex@host project]$ ./script.sh 5 8
The result is: 13

Hints

  • You can use nano to create and edit the script file.
  • Remember to make the script executable using the chmod command before running it.
  • In Bash, arithmetic operations can be performed using ((...)) or $[...] syntax. For example, result=$((num1 + num2)).
  • The echo command can be used to print the output to the terminal.
✨ Check Solution and Practice

Summary

In this challenge, you learned how to create a simple shell script that accepts input parameters and performs a basic operation using those parameters. You practiced creating a script file, making it executable, and accessing command-line arguments using $1 and $2. By understanding how to work with script inputs, you have gained a valuable skill that can be applied to more complex shell scripting tasks. This challenge helps reinforce the RHCSA exam objective of creating simple shell scripts and processing script inputs, which is essential for automating tasks in a Linux environment.