Assignment InstructionsTask:1. Create A Script Called Filter_numbers.sh That Accepts A List Of Numbers As Arguments.2. Use A For Loop To Iterate Through The Arguments And Print Only The Numbers Greater Than 10.3. Use Grep And Regular Expressions
Task Overview
In this task, we will create a shell script called filter_numbers.sh
that accepts a list of numbers as arguments. The script will use a for
loop to iterate through the arguments and print only the numbers greater than 10. Additionally, we will use grep
and regular expressions to filter the numbers.
Step 1: Create the Shell Script
To create the shell script, we will use a text editor to create a new file called filter_numbers.sh
. We will then add the following code to the file:
#!/bin/bash

if [ $# -eq 0 ]; then
echo "Error: No arguments provided"
exit 1
fi
for num in "@"; do
if (( num > 10 )); then
echo "num"
fi
done
Explanation of the Code
- The first line
#!/bin/bash
specifies the interpreter that should be used to run the script. - The
if
statement checks if the user provided any arguments. If not, it prints an error message and exits the script. - The
for
loop iterates through the arguments passed to the script. The"$@"
syntax allows us to access all the arguments as separate variables. - Inside the loop, we use a conditional statement
if (( num > 10 ))
to check if the current number is greater than 10. If it is, we print the number.
Step 2: Make the Script Executable
To make the script executable, we need to give it execute permissions. We can do this by running the following command:
chmod +x filter_numbers.sh
Step 3: Test the Script
To test the script, we can save it to a file called filter_numbers.sh
and then run it with some sample arguments:
./filter_numbers.sh 5 15 20 8 12
This should print the numbers 15, 20, and 12, which are greater than 10.
Using grep
and Regular Expressions
We can also use grep
and regular expressions to filter the numbers. Here's an example of how we can modify the script to use grep
:
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Error: No arguments provided"
exit 1
fi
echo "@" | grep -E '^[0-9]+' | grep -E '[1][0-9]+