2016-02-11 131 views
1

我有一个问题。我需要阅读用户输入,但我需要用户输入4行。每次用户按下输入它终止读取命令,所以我没有读取命令4次(不知道这是否正确) - 我需要帮助。 另外我如何输出用户的输入到文件?而且输出也需要4条线。请看我的剧本。 我感谢任何帮助。Shell脚本 - 从用户输入4行

1 #!/bin/bash 


2 #Displaying user name, host name, time, and date 

3 Time=`date +%r` 
4 Date=`date +%m/%d/%Y` 
5 echo "$USER is running this script on $HOST at $Time on $Date:" 
6 echo"" 
7 echo "Please enter 4 lines of text: " 
8 read line1 
9 read line2 
10 read line3 
11 read line4 
12 echo "I'm now putting the four lines you entered into a text file called \"mylines.txt\"..." 
13 echo $line1\n $line2\n $line3 \n$line4 > lines.txt 
14 echo"" 
15 echo "The lines you entered were:\n$line1\n$line2\n$line3\n$line4" 
16 echo"" 
+0

重复'read'命令就可以了。对于写入文件,使用'echo -e“$ line1 \ n $ line2 \ n ...”> lines.txt'(不含空格)或重复'echo $ 1> lines.txt','echo $ line2 >>行.txt等 – jofel

回答

2

要阅读4条线,你可以使用一个循环,并将其存储在一个数组:

#!/bin/bash 

lines=() 
echo "Please enter 4 lines of text: " 
for ((i=1; i<=4; i++)); do 
    IFS= read -p "Enter line $i: " -r line && lines+=("$line") 
done 

然后进行打印,并将其重定向:

printf "%s\n" "${lines[@]}" > lines.txt 
+0

当我尝试运行它时,它会告诉我语法错误:“(”unexpectedly for'lines =()' –

+0

您可能不使用'bash'来执行它。使用'bash。/ script.sh' – anubhava

+0

所以我无法运行它作为'./ script.txt'?因为这是我的教授想要它做的 –

1

我不知道,如果一个得到你想要的... 但看到这个和平的代码

#!/bin/bash 

myfile="file" 

echo "a line im my file" > $myfile 
echo "now a erased my file and create another with the same name" > $myfile 
echo "now I'm writing at the end of my file" >> $myfile 
echo " 



now I put some lines in the end of my file" >> $myfile 

如果你想要的是把一些行到你的文件,你可以这样做:

echo $line1 > lines.txt 
echo " 



" + $line2 >> lines.txt 
echo " 



" + $line3 >> lines.txt 
echo " 



" + $line4 >> lines.txt 

如果它只是,这种高度重视和做;)