Jiachang  Yang
Jiachang Yang

Reputation: 200

Use bash script to read numbers

Write a bash script that will read 10 integers from users and append the output to a file ‘XYZ’. You are not allowed to use the ‘read’ statement more than once in the script.

#! /bin/bash

for i in {0,1,2,3,4,5,6,7,8,9}
do
    read "i"
    echo "0,1,2,3,4,5,6,7,8,9" >> XYZ
done

I am a student just bengin to learn this, I feel it is difficult, could you give me some suggestions? I think this should have many problems. Thank you very much.

Upvotes: 3

Views: 14184

Answers (3)

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17188

Read 10 (or less,or more) integers into an array, output not more than the first 10:

read -p '10 integers please: ' -a number 
IFS=,
echo  "${number[*]:0:10}" >> XYZ

Input:

1 2 3 4 5 6 7 8 9 0

Output, comma separated:

1,2,3,4,5,6,7,8,9,0

Upvotes: 1

plesiv
plesiv

Reputation: 7028

#!/bin/bash
echo 'Input 10 integers separated by commas:'
read line
nums=`echo -n "$line" | sed "s/,/ /g"`
for i in $nums; do
    echo "$i" >> XYZ
done

If you input 9,8,7,6,5,4,3,2,1,0, those numbers will be appended to the XYZ file, each one in a new line.

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Let's see what you already have. Your for loop does 10 iterations of a read command, and read appears only once in the script. You also append (>>) your output to the file XYZ.

You shouldn't use the same variable for loop counter and reading the input, though. And the sequence could be shortened to {0..9}.

What you're still missing is a condition to check that the user input actually is an integer. And you're probably supposed to output the value you read, not the string "0,1,2,3,4,5,6,7,8,9".


On a more general note, you may find the following guides helpful with learning bash:

Upvotes: 5

Related Questions