Create a Conditional Shell Script

LinuxLinuxBeginner
Practice Now

Introduction

In this challenge, you will learn how to create a simple shell script that uses conditional statements to execute code based on certain conditions. This is a fundamental skill required for the RHCSA exam, as it allows you to write more complex and dynamic scripts that can adapt to different scenarios.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") subgraph Lab Skills linux/echo -.-> lab-389443{{"`Create a Conditional Shell Script`"}} end

Create a Conditional Shell Script

Tasks

  • Create a shell script that checks the number of command-line arguments provided.
  • If the script is called with no arguments, print a message indicating that the script requires at least one argument.
  • If the script is called with one argument, print a message indicating that the script was called with one argument.
  • If the script is called with more than one argument, print a message indicating that the script was called with multiple arguments.

Requirements

  • The shell script should be named conditional_script.sh and should be located in the ~/project directory.
  • The script should use the if-elif-else construct to handle the different cases.
  • The script should use the test command or the [] syntax to check the number of arguments.
  • The script should use echo or printf to print the appropriate messages.

Example

$ ./conditional_script.sh
This script requires at least one argument.
$ ./conditional_script.sh one
This script was called with one argument.
$ ./conditional_script.sh one two three
This script was called with multiple arguments.

Summary

In this challenge, you learned how to create a simple shell script that uses conditional statements to execute code based on the number of command-line arguments provided. This is an essential skill for the RHCSA exam, as it allows you to write more dynamic and adaptable scripts that can handle different scenarios. By completing this challenge, you have demonstrated your ability to use if-elif-else constructs, the test command, and the [] syntax to create a conditional shell script.

Other Linux Tutorials you may like