我的外壳脚本有一些问题,我写了一个很短的例子,但我没有得到预期的输出,我在case语句中使用了if条件,但有一些失败。
好吧,我的问题是:
当我按下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发布于 2014-10-28 20:03:09
几个问题:
$directory = "/test/sample/“fi
赋值时不使用$,因此应使用like
directory="/test/sample/“fi
$directory = "/test/sample/“fi
你为什么需要方括号?你在做ls /test/sample吗?去掉它就行了。
如果"$directory“= "”
如果用户只按enter,那么它不会工作,所以你应该这样做:
如果"X$directory“= "X”目录,您可以组合ls并查找如下所示:
find "$directory“-name "$search”-type f -exec ls -l {} \;
发布于 2014-10-28 22:27:05
这是一个添加了一些格式化编辑和注释的工作示例。您需要对搜索文件名进行一些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
donehttps://stackoverflow.com/questions/26607594
复制相似问题