Create Shell Scripts With Loops

LinuxLinuxBeginner
Practice Now

Introduction

In this challenge, you will learn how to create a simple shell script that uses looping constructs (such as for and while) to process file or command-line input. Shell scripting is a powerful tool for automating repetitive tasks and streamlining your workflow. By completing this challenge, you will gain hands-on experience in developing shell scripts that can handle dynamic input and perform various operations.


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-389452{{"`Create Shell Scripts With Loops`"}} end

Create a Shell Script with a for Loop

Tasks

  • Create a shell script that uses a for loop to iterate through a list of files in a directory and perform an operation on each file.
  • The script should accept a directory path as a command-line argument.
  • For each file in the directory, the script should print the file name and its contents.

Requirements

  • The script should be named list_files.sh and be located in the ~/project directory.
  • The script should use a for loop to iterate through the files in the directory specified as a command-line argument.
  • For each file, the script should print the file name and its contents.
  • The script should work for any directory path provided as a command-line argument.

Example

$ ./list_files.sh ~/project
File: file1.txt
Content of file1.txt
File: file2.txt
Content of file2.txt
File: file3.txt
Content of file3.txt

Summary

In this challenge, you learned how to create a simple shell script that uses a for loop to iterate through a list of files in a directory and perform an operation on each file. You practiced writing a script that accepts a command-line argument, checks if the argument is valid, and then processes the files in the specified directory. This challenge helps you develop the skills to create more complex shell scripts that can automate various tasks and handle dynamic input.

If you need to set up the initial environment for this challenge, you can use the following setup.sh script:

#!/bin/bash

## Create some sample files in the ~/project directory
mkdir -p ~/project
echo "Content of file1.txt" > ~/project/file1.txt
echo "Content of file2.txt" > ~/project/file2.txt
echo "Content of file3.txt" > ~/project/file3.txt

You can run this script as the labex user to set up the initial environment for the challenge.

Other Linux Tutorials you may like