repeat functions in shell script 2

General support questions
Post Reply
knzzz
Posts: 157
Joined: 2017/02/25 12:41:42

repeat functions in shell script 2

Post by knzzz » 2018/04/02 17:03:30

Hi Team,

i need to repeat a function n number of times, whereas 1..n is a value which should be inside a same function, how to exactly repeat n number of times and each value shld get subsitiuted for each and every fn


repeat(){

for i in {1.."$n"}

do

echo "$n"

done

exit 0

}


read -p "Enter the value of n:" n


repeat


-------------------------------------------------------------------

n value i will give , so that n = 5

then i shold get o/p

1
2
3
4
5

User avatar
fdisk
Posts: 42
Joined: 2017/11/04 00:59:56

Re: repeat functions in shell script 2

Post by fdisk » 2018/04/05 15:38:06

for i in {1.."$n"}
Look out: Bash brace expansion takes place before variable expansion. In this case 1.."$n" will be interpreted as a single string *before* variable is expanded. Conclusion: i will only loop through one single string element -> this is not what you want.

Instead you're probably looking for something like this:

Code: Select all

repeat() {
    i=1
    while [ "$i" -le "$1" ]; do
        echo "$i";
        i=$(($i + 1))
    done
}
read -p "Enter the value of n:" n
repeat $n 

Post Reply