Jack D
Jack D

Reputation: 21

Bash - Repeat a input n amount of times (user inputted)

So I have a little bit of bash that I am struggling with. Basically I am taking a users input ($time) between 1 and 10 and a predefined word ($word) that a user inputted earlier and I want it to echo the $word, $time times.

My attempt:

while [[ $time -le 10 ]]
do
    echo $word
    time=$((time + 1))
done

Any help is very much appreciated!

Upvotes: 1

Views: 257

Answers (4)

Walter A
Walter A

Reputation: 20002

yes repeats things.

time=6
yes "$word" | head -$time

Upvotes: 2

Mike Q
Mike Q

Reputation: 7327

What you have done seems fine but I provided an example using 'seq' for your reference.

Expanding on what you are doing, you can check the input using something like a while loop or a case statement. Basically check that the user has inputted something that is either 1-9 or 10. In this case I used an IF statement with regex. Lets see if you can do the same for the input word? maybe check that it isn't empty and force them to input something that contains numbers and/or characters etc?

Example:

#!/bin/bash
echo "Please input a word:"
read -r word

# force a while number is not 1-9 or 10 keep asking for a number.
while [[ 1 ]] ; do
  echo "Input value from 1 - 10"
  read -r inval
  if [[ $inval =~ ^[1-9]$|10 ]] ;then
    echo "Number $inval is a good pick, lets go!"
    break
  else
    echo "Sorry, please choose from 1-10"
  fi
done
# simple example using 'seq' from 1 to inputted value
for i in $(seq 1 "${inval}"); do
  echo "${word}"
done

Sample output:

Please input a word:
Hello World !
Input value from 1 - 10
11
Sorry, please choose from 1-10
Input value from 1 - 10
what
Sorry, please choose from 1-10
Input value from 1 - 10
10
Number 10 is a good pick, lets go!
Hello World !
Hello World !
Hello World !
Hello World !
Hello World !
Hello World !
Hello World !
Hello World !
Hello World !
Hello World !

Further reading: How do I iterate over a range of numbers defined by variables in Bash?

Upvotes: 0

symlink
symlink

Reputation: 12209

function run() {
    number=$1
    word=$2
    for n in $(seq $number); do
      echo "$word";
    done
}

run 5 "hello"

Output:

hello
hello
hello
hello
hello

Upvotes: 1

Cyrus
Cyrus

Reputation: 88583

With a for loop:

time="3"
word="hello"
for ((i=0; i<$time; i++)); do echo "$word"; done

Output:

hello
hello
hello

Upvotes: 1

Related Questions