有幾個微妙的東西可以幫助你的腳本。在讀取文件名之前,您應該設置IFS
(內部字段分隔符),使其僅在newline
處中斷。這將確保您獲得完整的文件名,如果它包含空格並且沒有被引用。讀取文件名後恢復IFS
。您還需要檢查$line
是否已在read
之後被讀取,以確保在數據文件最後一行末尾沒有newline
的情況下得到最後一行。
此外,每當你從用戶讀取一個文件名,你應該確認它是一個有效的文件名試圖從中讀取數據之前:
#!/bin/bash
oifs=$IFS # save internal field separator
IFS=$'\n' # set IFS to newline (if whitespace in path/name)
echo -n "Enter file path/name: " # suppress newline
read fname # read full-path/filename
IFS=$oifs # restore default IFS=$' \t\n'
[ -r "$fname" ] || { # validate input file is readable
printf "error: invalid filename '%s'\n" "$fname"
exit 1
}
while read line || [ -n "$line" ] # protect against no newline for last line
do
name=$line
echo "Text read from file - $name"
done < "$fname" # double-quote fname
exit 0
樣品使用/輸出:
$ bash readfn.sh
Enter file path/name: dat/ecread.dat
Text read from file - read: 4163419415 0 0 4163419415 0 4395.007 0
Text read from file - read: 4163419415 0 0 4163419415 0 4395.007 0
Text read from file - read: 4163419415 0 0 4163419415 0 4395.007 1
Text read from file - read: 4163419415 0 0 4163419415 0 4395.007 0
非常感謝你的答案,但我只是在一個點混淆。 爲什麼你在這裏使用-r: [-r「$ fname」] || {#驗證輸入文件可讀 printf「錯誤:無效文件名'%s'\ n」「$ fname」 exit 1 } – Umair 2014-11-26 22:44:25
您可以使用'-e'(是否存在),'-f'它是一個文件)等,但最具體的是'-r'(它是可讀的[它包含存在,作爲一個文件,並且具有足夠的權限來閱讀])。或者你可以把握機會,而不是測試(不推薦)。重點在於,在驗證之前,任何用戶輸入都應該被視爲**可疑**。不知道將會輸入什麼。 – 2014-11-27 00:17:18
非常感謝。'|| ||這意味着OR,對嗎?對不起,這樣noob問題,但我剛剛開始.. – Umair 2014-11-27 00:24:30