需要帮助打印特定菜单的shell脚本

时间:2017-04-18 12:41:49

标签: linux bash shell scripting

我是linux和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命令来执行所声明的功能,提示用户输入任何必要的参数。例如,如果用户选择“'”,则提示用户输入文件名,然后打印出文件内容。

到目前为止,我已经做到了这一点,但我希望选项是字母而不是数字,如前所述。可能是一个更好,更清晰的脚本。

#!/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

1 个答案:

答案 0 :(得分: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

示例输出:

[root@localhost ~]# 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

注意:[抄送] *) - 这意味着任何以C / c开头的名称作为输入它将接受,如果您只需要一个字母作为输入,则在每个案例中删除*(星号),说[C])< / p>

希望这对你有所帮助。