使用 bash 脚本读取数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15731851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use bash script to read numbers
提问by Jiachang Yang
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.
编写一个 bash 脚本,该脚本将从用户那里读取 10 个整数并将输出附加到文件“XYZ”中。不允许在脚本中多次使用“read”语句。
#! /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.
我是刚开始学这个的学生,感觉很难,能给点建议吗?我想这应该有很多问题。非常感谢。
回答by Ansgar Wiechers
Let's see what you already have. Your forloop does 10 iterations of a readcommand, and readappears only once in the script. You also append (>>) your output to the file XYZ.
让我们看看你已经拥有了什么。您的for循环对一个read命令执行 10 次迭代,并且read只在脚本中出现一次。您还可以将>>输出附加 ( ) 到文件中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}.
但是,您不应该对循环计数器和读取输入使用相同的变量。并且该序列可以缩短为{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".
您仍然缺少一个条件来检查用户输入实际上是一个整数。而且您可能应该输出您读取的值,而不是 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:
更一般地说,您可能会发现以下指南对学习有所帮助bash:
回答by plesiv
#!/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 XYZfile, each one in a new line.
如果您输入9,8,7,6,5,4,3,2,1,0,这些数字将附加到XYZ文件中,每个数字都在一个新行中。
回答by Fritz G. Mehner
Read 10 (or less,or more) integers into an array, output not more than the first 10:
将 10 个(或更少或更多)整数读入数组,输出不超过前 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

