2017-04-18 87 views
0

我是linux和shell腳本的新手。我需要寫一個shell腳本,打印以下菜單:在打印特定菜單的shell腳本中需要幫助

C)hange into a directory 
L)ist the files in current directory 
M)ove a file 
K)opy a file 
P)rint the contents of a file 

該腳本應讀取用戶的選擇和使用合適的shell命令來執行所陳述的功能,提示輸入任何必要的參數的用戶。例如,如果用戶選擇'p',提示用戶輸入文件名,並打印出文件的內容。

到目前爲止,我已經做到了這一點,但我希望選項可以是字母而不是數字,如前所述。可能更好,更乾淨的腳本。

#!/bin/bash 
# Bash Menu Script Example 

PS3='Please enter your choice: ' 
options=("C)hange into a directory" "L)ist the files in the current 
directory" "M)ove a file" "K)opy a file" "P)rint the contents of a file" "Quit") 
select opt in "${options[@]}" 
do 
case $opt in 
"C)hange into a directory") 
echo "you chose choice 1" 
echo -n "Enter a directory to change into" 
read answer 
cd $answer 
pwd 
;; 
"L)ist the files in the current directory") 
echo "you chose choice 2" 
echo -n "Listing the files in the current directory" 
ls -ltr ./ 
;; 
"M)ove a file") 
echo "you chose choice 3" 
echo -n "Enter a file name to move" 
read answer 
mv $answer /tmp 
;; 
"K)opy a file") 
echo "you chose choice 3" 
echo -n "Enter a file to copy" 
read answer 
cp $answer /tmp 
;; 
"P)rint the contents of a file") 
echo "you chose choice 3" 
echo -n "Print to contents of a file" 
read answer 
cat $answer 
;; 
"Quit") 
break 
;; 
*) echo invalid option;; 
esac 
done 

回答

2

樣品下面的腳本,做出相應的變化,

示例腳本

#!/bin/bash 

while true; do 
echo -e "\nPlease enter a Letter : \nP - Print Date \nE - Exit" 
read value 
case $value in 
    [Pp]*) echo `date`;; 
    [Ee]*) exit;; 
    *) echo "\nPlease P or E";; 
esac 
done 

樣本輸出:

[[email protected] ~]# sh my.sh 

Please enter a Letter : 
P - Print Date 
E - Exit 
p 
Tue Apr 18 06:29:15 PDT 2017 

Please enter a Letter : 
P - Print Date 
E - Exit 
E 

在你的情況下,該腳本將像,

#!/bin/bash 
# Bash Menu Script Example 

while true; do 
echo -e "\nPlease enter your choice: " 
echo -e "\n(C)Change into a directory\n(L)ist the files in the current directory \n(M)Move a file \n(K)Copy a file \n(P)Print the contents of a file \n(Q)Quit\n" 
read opt 
case $opt in 
[Cc]*) 
echo "you chose choice 1" 
echo -n "Enter a directory to change into" 
read answer 
cd $answer 
pwd 
;; 
[Ll]*) 
echo "you chose choice 2" 
echo -n "Listing the files in the current directory" 
ls -ltr ./ 
;; 
[Mm]*) 
echo "you chose choice 3" 
echo -n "Enter a file name to move" 
read answer 
mv $answer /tmp 
;; 
[Kk]*) 
echo "you chose choice 3" 
echo -n "Enter a file to copy" 
read answer 
cp $answer /tmp 
;; 
[Pp]*) 
echo "you chose choice 3" 
echo -n "Print to contents of a file" 
read answer 
cat $answer 
;; 
[Qq]*) 
break 
;; 
*) echo invalid option;; 
esac 
done 

注意:[Cc] *) - 這意味着任何名稱以C/c作爲輸入,它將接受輸入,如果您只需要一個字母作爲輸入,則刪除每個事例的*(星號),例如[C])

希望這可以幫助你。

+1

非常感謝。請同時告訴我們[C]是否會區分大小寫或者輸入'C'或'c'? –

+0

@AhmedDildar - 它的大小寫敏感,所以它的工作取決於你申報的信。 –