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.

2 Likes

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.

1 Like

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

2 Likes

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

#!/bin/bash
arguments=$@
#transforming the arguments in an array:
IFS=’ ’ read -r -a argumentsArr <<< $arguments
length=$#
i=$length
while [ $i -ge 0 ]
do
echo ${argumentsArr[$i]}
((i=i-1))
done

Also, why isn’t this working: ?

#!/bin/bash
#transforming the arguments in an array:
IFS=’ ’ read -r -a argumentsArr <<< $@
length=$#
while [ $length -ge 0 ]
do
echo ${argumentsArr[$length]}
((length=length-1))
done

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:

#!/bin/bash
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:

./script.sh arg1 arg2 arg3

2 Likes