-1

I need to get user input for a number and then write a name row by row in linux terminal that much amount of times that user inputed. Example if I lets say chose a number 2 the program will write Name 2 times row by row. I wrote some code but I cant figure where is the mistake. I think its the loop where the mistake is.

echo "Please enter a number "
read $number

for value in {$number}
do
echo "Name"
done
Inian
  • 80,270
  • 14
  • 142
  • 161

2 Answers2

0

To read input and save it into a variable named number, do:

read number

To get the value of number, do $number or ${number}. Remove the { } in the {$number} or shift $ with {.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Thank you soo much now the program asks for a number I enter the value but it isnt displaying any of tekst that said names – MarlboroMolly Dec 30 '19 at 10:59
0

Just do:

echo "Please enter a number "
read number
if ! test "$number" -gt 0 2> /dev/null; then
    echo "You must enter an integer greater than 0" >&2
    exit 1
fi
yes Name | sed ${number}q

But don't prompt for the number. Take it as a command line argument, and just do

yes Name | sed "${1}q"

Let sed generate the error message if the parameter is invalid.

The trouble with your loop is that for value in $number takes the string $number and breaks it on whitespace (depends on IFS, actually, but let's not get bogged down by details) and iterates over each value. That is, if $number is the string 1 3 dog 5, then the loop will iterate 4 times with $value taking the values 1, 3, dog, and 5. If $number is 7, then the loop iterates exactly once. You could do for((i=0; i < $number; i++)); do ..., but that does not generate any useful error message if $number is not an integer.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • THANK YOU SOO MUCH the code works now I get what I didnt do right I was telling my code to read the number value but never to print that amount of times. THANK YOU – MarlboroMolly Dec 30 '19 at 11:19