[英]Shell scripting - inputting 4 lines from the user
我有個問題。 我需要讀取用戶輸入,但我需要用戶輸入4行。 每次用戶按下輸入時,它都會終止讀取命令,所以我讀了4次命令(不確定這是否正確) - 我需要幫助。 另外如何將用戶輸入輸出到文件中? 而那個輸出也需要我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""
要讀取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
我不確定是否能得到你想要的......但是看看代碼的安靜
#!/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
如果只是這樣,這可以做;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.