<aside> 🗣 By Shathin Rao [MT2020067]
</aside>
<aside>
📌 The following content is in the following format -
Question - The given question.
Answer - A short description about the script.
Code block 1 - The code editor - Shows the script's code.
Code block 2 - The terminal - Shows the output(s) of the script.
</aside>
[Question] Write a shell script to count the number of block device files in /dev directory.
[Answer] The shell script 1-counting-block-files.sh uses three commands - ls, grep and wc to count the number of block files in the /dev directory. The shell script does not take in any command line argument nor does it take any user input (through read).
#! /bin/bash
echo -e "The number of block device files in the /dev directory is: \c"
ls -la /dev | grep ^b | wc -l
# Executing the shell script
$ ./1-counting-block-files.sh
The number of block device files in the /dev directory is: 18
[Question] Write a shell program that checks the number of command line arguments and echoes an error message if there are not exactly three arguments or echoes the arguments themselves if there are three.
[Answer] The shell script 2-cmd-line-args.sh accepts command line arguments. It uses the $# variable to count the number of command line arguments passed to the script and then access the arguments passed to it using the $@ variable.
#! /bin/bash
if [ $# -ne 3 ]
then
echo "ERROR: More / less than 3 command line arguments were passed to this script!"
else
args=("$@")
echo "Argument 1: ${args[0]}"
echo "Argument 2: ${args[1]}"
echo "Argument 3: ${args[2]}"
fi
$ # Executing the shell script
$ # Output 1 - No errors
$ /2-cmd-line-args.sh a b c
Argument 1: a
Argument 2: b
Argument 3: c
$ # Output 2 - Error
$ ./2-cmd-line-args.sh
ERROR: More / less than 3 command line arguments were passed to this script!
[Question] Write a shell program called new_files that will accept a variable number of command line arguments. The shell program will create a new file associated with each command line argument and echo a message that notifies the user as each file is created.
[Answer] The script 3-create-new-files.sh accepts the file names (with extension) as the command line arguments to the script. It uses the touch command to create the new files in the current working directory and echoes a message when each file is created.
#! /bin/bash
if [ $# -gt 0 ]
then
file_names=("$@")
for (( iter=0; iter<$#; iter++ ))
do
touch ${file_names[iter]}
echo "The file ${file_names[iter]} has been created..."
done
else
echo "Please provide file names as the argument to this script!"
fi
$ # Executing the shell script
$ # Output 1 - No errors
$ ./3-create-new-files.sh file1.txt file2.txt
The file file1.txt has been created...
The file file2.txt has been created...
$ # Output 2 - Error
$ ./3-create-new-files.sh
Please provide file names as the argument to this script!