2012-02-14 82 views
2

我從來沒有做過shell腳本之前,需要一些幫助,一個小項目。檢查用戶輸入的三種文件名作爲輸入

我希望用戶輸入三種文件名,並檢查用戶已經輸入了三個名字,如果它或多或少給出錯誤。該文件將被分類到另一個文件,但被工作正常只是有問題,檢查用戶輸入的內容。

我已經試過

echo Please select the three files you want to use 
read $file1 $file2 $file3 

if ! [ $# -eq 3 ]; then 
    echo "Please enter THREE values" 
fi 

回答

3

不改變你read命令:

 
if [ -z "$file1" -o -z "$file2" -o -z "$file3" ]; then 
    echo "Please enter THREE values" 
fi 

但首選的方式在這裏使用數組:

 
read -a files 
if [ ! ${#files[@]} -eq 3 ]; then 
    echo "Please enter THREE values" 
fi 

而且順便說一句。元素是${files[0]}${files[1]}${files[2]}或者,你可以循環數組:

 
for f in "${files[@]}"; do 
    echo $f 
done 
+0

謝謝你這個完美的作品,也非常感謝你添加元素以及爲我節省了一些時間在尋找這些。 – Splendid 2012-02-14 17:09:29

+0

沒有問題,upvote ??? :-) – 2012-02-14 17:12:31

+1

我想我選擇答案的那一刻,但需要對這份排名15,仍然只有13,將給予好評的那一刻,我可以答應 – Splendid 2012-02-14 17:35:48

0

你做的很好,唯一的問題是在你讀的語句中使用$。刪除美元和您的代碼將工作:

#!/bin/sh 

echo "Please select the three files you want to use" 
read file1 file2 file3 

#Or something like: 
#echo -n "File 1:" 
#read file1 
#echo -n "File 2:" 
#read file2 
#echo -n "File 3:" 
#read file3 

echo "File 1: $file1 File 2 : $file2 File 3 : $file3"