Search code examples
bashfunctionechocounter

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-5 then show the list of outputs according to chosen number 
so

if 2 then act as following: 
echo "one" <------start here
echo "two" <------stop here
echo "three"

the end output put will be:

one 
two

if 3 then act as following:
echo "one" <------start here
echo "two" 
echo "three" <------stop here

the end output will be:

one
two
three

I need it in one function. I know it can be done the hard way, as following:

#!/bin/bash

if [[ $num = 1 ]]; then
echo "one"
fi

if [[ $num = 2 ]]; then
echo "one"
echo "two"
fi

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

  • You can use a loop if you store the data you need in an associative array:

    #!/usr/bin/env bash
    numbers=( [1]="one" [2]="two" [3]="three" [4]="four" [5]="five" )
    
    max=${1:-5} # either use $1 or default to 5 if empty
    
    for ((i=1; i<=max; i++)); do
      echo "${numbers[$i]}"
    done
    

    If this script is named f, behavior is as follows:

    $ f 2
    one
    two
    
    $ f 5
    one
    two
    three
    four
    five
    

    If your real use case involves running completely arbitrary commands, then your code might look more like the following:

    #!/usr/bin/env bash
    steps=( [1]=step_one [2]=step_two [3]=step_three [4]=step_four [5]=step_five )
    max=${1:-5}
    
    step_one()   { echo "one"; }
    step_two()   { echo "two"; }
    step_three() { echo "three"; }
    step_four()  { echo "four"; }
    step_five()  { echo "five"; }
    
    for ((i=1; i<=max; i++)); do
      "${steps[$i]}"
    done