2017-02-25 53 views
3

我有一個shell腳本,我希望在腳本執行時提示用戶輸入一個對話框輸入。如何提示用戶輸入shell腳本?

例如(劇本之後開始):

"Enter the files you would like to install : " 

user input : spreadsheet json diffTool 

where $1 = spreadsheet, $2 = json, $3 = diffTool 

然後在每個用戶輸入迴路,並完成類似

for var in "[email protected]" 
do 
    echo "input is : $var" 
done 

我怎麼會去我的shell腳本中這樣做呢?

預先感謝您

+0

請參閱:'help read' – Cyrus

+1

我會將文件名作爲命令行參數傳遞。這就是任何UNIX工具或多或少的工作原理。 – hek2mgl

+0

請在查詢之前考慮[搜索](https://www.google.com/webhp#q=bash+prompt+for+input)。這個確切的問題,和其他人一樣,已經被問了很多次。 – dimo414

回答

5

您需要使用read內置提供bash和存儲多個用戶輸入到變量,

read -p "Enter the files you would like to install: " arg1 arg2 arg3 

給你用空格分開輸入。例如,運行上面的時候,

Enter the files you would like to install: spreadsheet json diffTool 

現在每個上面輸入是在變量可用arg1arg2arg3


上述部分回答了這樣的問題,你可以輸入用戶輸入一行一行空格分開,但如果您有興趣在一個循環中讀取多個,用多個提示,這裏是你如何在bash shell中做的。下面獲取用戶輸入的邏輯,直到輸入鍵被按下,

#!/bin/bash 

input="junk" 
inputArray=() 

while [ "$input" != "" ] 
do 
    read -p "Enter the files you would like to install: " input 
    inputArray+=("$input") 
done 

現在所有的用戶輸入存儲陣列inputArray,你可以遍歷讀值英寸要打印他們都在一個鏡頭,做

printf "%s\n" "${inputArray[@]}" 

或者更合適的循環將

for arg in "${inputArray[@]}"; do 
    [ ! -z "$arg" ] && printf "%s\n" "$arg" 
done 

和訪問單個元素"${inputArray[0]}""${inputArray[1]}"等。