2016-04-15 70 views
0

我的腳本從用戶處獲取站點名稱。Bash爲用戶選擇編號結果

./run_script <site> 

./run_script cambridge 

然後,它允許用戶通過腳本簽出,編輯和提交對文件的更改。

但是,有些網站有兩到六個文件。

所以腳本列出它們如下

你有一個以上的劍橋文件。

請從以下挑選:

cambridge1

cambridge2

cambridge3

用戶輸入字劍橋[1-3]

然而,我我想爲每個變量賦值,即如下。

請選擇您想要的選項:

1)。 cambridge1

2)。 cambridge2

3)。 cambridge3

用戶輸入1,2或3,然後它讀取文件。

當前的代碼我已經是:

echo $(tput setaf 5) 
echo "Please choose from the following: " 
echo -n $(tput sgr0) 

find path/to/file/. -name *"$site"* | awk -F "/" '{print $5}' | awk -F "SITE." '{print $2}' 

echo $(tput setaf 3) 

read -r input_variable 
echo "You entered: $input_variable" 
echo $(tput sgr0) 
+4

聽起來像是'select'工作。請參閱Bash參考手冊的[conditional constructs部分](https://www.gnu.org/software/bash/manual/bashref.html#index-commands_002c-conditional)。 'select'是'if'和'case'之後的第三個構造。 – kojiro

+0

嗯..謝謝,我會試試這個,看看它是否可以拿起不同的數量。--Ben –

回答

1

這裏有一個有趣的方式:

# save the paths and names of the options for later 
paths=`find path/to/file/. -name "*$site*"` 
names=`echo "$paths" | awk -F "/" '{print $5}' | awk -F "SITE." '{print $2}'` 
# number the choices 
n=`echo "$names" | wc -l` 
[ "$n" -gt 0 ] || echo "no matches" && exit 1 
choices=`paste <(seq 1 $n) <(echo "$names") | sed 's/\t/). /'` 

echo "Please choose from the following: " 
echo "$choices" 
read -r iv 
echo "You entered: $iv" 
# make sure they entered a valid choice 
if [ ! "$iv" -gt 0 ] || [ ! "$iv" -le "$n" ]; then 
    echo "invalid choice" 
    exit 1 
fi 

# name and path of the user's choice: 
name_chosen=`echo "$names" | tail -n+$iv | head -n1` 
path_chosen`echo "$paths" | tail -n+$iv | head -n1` 
+1

謝謝韋伯,這很完美。 –