Practice Exercise in Bash Basics Series #3: Pass Arguments and Accept User Inputs

If you are following the Bash Basics series on It’s FOSS, you can submit and discuss the answers to the exercise at the end of the chapter:

Fellow experienced members are encouraged to provide their feedback to new members.

Do note that there could be more than one answer to a given problem.


Some addition to that:

$1, $2…$n Script arguments

If n>9 special syntax is needed. This example is snipped from my script which uses dcfldd to write image to pendrives:
dcfldd if=$1 of=$2 of=$3 of=$4 of=$5 of=$6 of=$7 of=$8 of=$9 of=${10} of=${11} bs=64K status=on

$1 is the imagefile’s name, arguments 2 to 11 are the /dev/sdX names, where to flash the image. Note the ${10}, which is not $10, as it could be expected.


That’s a good suggestion. I am going to add it in the tutorial. Thanks :pray:


Hi, I tried to answer the question of your exercise 1: can I ask you a help in making the code cleaner?

#transforming the arguments in an array:
IFS=’ ’ read -r -a argumentsArr <<< $arguments
while [ $i -ge 0 ]
echo ${argumentsArr[$i]}

Also, why isn’t this working: ?

#transforming the arguments in an array:
IFS=’ ’ read -r -a argumentsArr <<< $@
while [ $length -ge 0 ]
echo ${argumentsArr[$length]}

thank you!

Hello @leonardo091800

Good job on doing the exercises.

You want to make your script generic so that it could handle any number of arguments provided to it. That’s good thinking :clap:

However, this exercise is for beginners and hence limited in its approach. You have to provide three arguments to it and print them in reverse order.

Which is as straight forward as this:

echo "Arguments in reverse order:"
echo "$3 $2 $1"

Sometimes things are simpler than they look :wink:

Now, about this question

It works fine in my test. Just ensure that you are running the script in the following fashion:

./ arg1 arg2 arg3


Exercise 3:

var= $(wc -l $1)
echo $var

1 Like

That can be accepted as an answer.

A further improvement would be to use cut or some other command to remove the filename from the output.

This gave me some trouble but i got it to work eventually. I’m sure it could be cleaned up, maybe get rid of file_path=“$path” and just put $path in directly?
I also added the continue prompt for when we learn if/then, I want to add “if no then exit” and "if no then go to “what is the file path”.


echo “Find line and word count for files”
echo “Continue?”
echo “What is the File Path?”
read path
echo “Is $path correct?”

#path to file

#line count
number_of_lines=$(wc --lines < $file_path)

#word count
number_of_words=$(wc --word < $file_path)

echo “Number of lines in file: $number_of_lines”
echo “Number of words in file: $number_of_words”