2017-04-18 66 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 - 它的大小写敏感,所以它的工作取决于你申报的信。 –