我的Shell脚本中有一些问题,
我写了一个很短的例子,但我得不到预期的输出,
我在if
声明中使用了case
条件,但有些失败。
好吧,我的问题是:
当我按2
时,用户应首先给出路径以搜索文件,如果没有给出路径,那么我将查看默认路径,如上所述,
但是我不能在这里得到这个功能,有人可以帮我解决这个问题吗?请
我很感谢你的帮助:)。
我的代码是:
#!/bin/bash
trap '' 2
while true
do
clear
echo -e " \t *******************************************************************"
echo -e " \t ******************** TEST-MENU ********************************"
echo -e "\t *******************************************************************"
echo -e "\n"
echo -e "\t\t 1)Show Date/Time"
echo -e "\t\t 2)File-Search"
echo -e "\t\t e)End \n"
echo -e "\t\t Select your choice:\c" ; read answer
echo -e "\t*******************************************************************"
case $answer in
1)date +'%y%m%d %H:%M:%S' ;;
2)echo -e "Please give your dir:\c" ; read directory
if [ "$directory" = "" ] then
$directory = "[/test/sample/]" fi
echo -e "Enter your file [$directory]:\c" ; read search
find "$directory" -name "*$search*" -type f -print|xargs ls -l ;;
e) exit ;;
esac
echo -e "Enter return to continue \c"
read answer
done
答案 0 :(得分:0)
几个问题:
变量作业
$ directory =" [/ test / sample /]"网络
在分配值时,您不会使用$,因此您应该使用类似
目录=" [/测试/样品/]"网络
您的默认目录
$ directory =" [/ test / sample /]"网络
为什么需要方括号?你在做ls [/ test / sample]吗?只需删除它。
你的if
if [" $ directory" ="" ]
如果用户只需按Enter键,那么它就无法工作,所以你应该这样做:
如果[" X $目录" =" X" ]
你可以组合ls并找到如下:
查找" $目录" -name" $ search " -type f -exec ls -l {} \;
答案 1 :(得分:0)
这是一个工作示例,其中添加了一些格式编辑和注释。你需要在搜索文件名上对null进行一些测试,就像它不存在一样,它显示了当前目录中的文件:
#!/bin/bash
trap '' 2
# Set up the default value. If you ever want to change it, just do it here.
# -r means make it read-only so this makes it a CONSTANT.
declare -r DEFAULT=1
while true
do
clear
echo -e " \t *******************************************************************"
echo -e " \t ************************ TEST-MENU ********************************"
echo -e "\t *******************************************************************"
echo -e "\n"
echo -e "\t\t 1)Show Date/Time"
echo -e "\t\t 2)File-Search"
echo -e "\t\t e)End \n"
# Typically in a prompt like this
# when there is a value in square brackets that means if you just
# press enter you will get that value as the default.
echo -e "\t\t Select your choice [$DEFAULT]: \c" ; read answer
echo -e "\t*******************************************************************"
# If nothing was selected, use the default.
# -z tests for null.
if [[ -z "$answer" ]]
then answer=$DEFAULT
fi
case $answer in
1) date +'%y%m%d %H:%M:%S'
;;
2) echo -e "Please give your dir: \c"
read directory
if [[ -z "$directory" ]] # Test for null
then directory="/test/sample/"
fi
echo -e "Enter your file [$directory]: \c"
read search
find "$directory" -name "*$search*" -type f -print|xargs ls -l
;;
e) exit
;;
# Always expect the unexpected! The * is the default for a case
# statement when no match is found.
*) echo -e "[$answer] is an invalid selection"
;;
esac
echo -e "Enter return to continue \c"
read answer
done