Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to build a function that will show a needed list of "echos"?

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading