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

Time:08-13

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

Bash has a built in called seq - from man seq -

NAME seq - print a sequence of numbers

So, if you just want to print the numbers -

seq 5

produces -

1
2
3
4
5

If you want the word "echo" attached - you can format the output with -f

seq -f "echo %2.0f" 5

This produces -

echo  1
echo  2
echo  3
echo  4
echo  5
  • Related