I want to make a function that will check a number between 1-5
and according to number it gets, it will output the amount of echo lines, as in following example:
if number 1 then show: echo "1"
if number 2 then show: echo "1" echo "2"
if number 3 then show: echo "1" echo "2" echo "3"
echo "1"
echo "2"
echo "3"
echo "4"
echo "5"
I know it can be done the hard way, as following:
#!/bin/bash
if [[ $num = 1 ]]; then
echo "1"
fi
if [[ $num = 2 ]]; then
echo "1"
echo "2"
fi
and so on…
but it will be too long if I will have to do it 50 times. I am sure there is an alternative way for that.
>Solution :
This is possibly more than you need, but it shows you how to count up to a specified number and use that counter to do something "useful".
#!/bin/bash
# Define the function:
function printNumbersTo() {
local -i number=${1} # -i forces the variable into an integer.
if [ "${number}" != "${1}" ]; then # Make sure the input parameter was an integer.
echo "'${1}' is not an integer."
return 1
fi
local -i counter=0
while [ ${counter} < ${number} ]; do
((counter++))
echo "Number is '${counter}'."
done
}
# Now call the function:
printNumbersTo 5