shell 脚本完成在目录或者文件中查找输入的内容,并且输出含有输入字符串的文件名称,但是得不到正确的结果。

czll520 2011-10-19 09:25:18
各位好,写了下面这个脚本,完成在目录或者文件中查找输入的内容,并且输出含有输入字符串的文件名称,但是得不到正确的结果。
估计在这一句话:
grep -l '$findstring' $targetpath$append
在下面echo出来了之后单独运行,又能正确出结果、小弟很纳闷。望各位高手解答,谢谢~!


#!/bin/sh
echo "请输入你要查找的内容:"
read findstring
echo "请输入你要超找的路径或者文件"
read targetpath
while test -z $findstring
do
echo "输入为空请重新输入:"
read findstring
done
while test -z $targetpath
do
echo "路径或者文件为空请重新输入:"
read targetpath
done
append='/*'
if test -d $targetpath || test -f $targetpath
then
grep -l '$findstring' $targetpath$append
echo $targetpath$append
echo "grep -l '$findstring' $targetpath$append"
else
echo "不是一个文件或者路径"
fi
...全文
338 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
o06v90o 2011-10-19
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 xiangliangyu2008 的回复:]
问题在这
if test -d $targetpath || test -f $targetpath
应该分开目录和文件
按你的脚本文件后面会加上/* 这肯定会错的

if test -d $targetpath || test -f $targetpath
then
if test -d $targetpath
then
echo "目录"
grep -l '$……
[/Quote]


grep -l '$findstring' $targetpath$append

这也得改,'里面的$findstring 并不会转换成具体值,改成双引号。
Linux-Torvalds 2011-10-19
  • 打赏
  • 举报
回复
#!/bin/sh
echo "请输入你要查找的内容:"
read findstring
echo "请输入你要超找的路径或者文件"
read targetpath
while test -z $findstring
do
echo "输入为空请重新输入:"
read findstring
done
while test -z $targetpath
do
echo "路径或者文件为空请重新输入:"
read targetpath
done
append="/*" #赋值错误,要双引号
if test -d $targetpath || test -f $targetpath
then
grep -l "$findstring" $targetpath$append #单引号不能变量扩展
echo $targetpath$append
echo "grep -l '$findstring' $targetpath$append"
else
echo "不是一个文件或者路径"
fi
Linux-Torvalds 2011-10-19
  • 打赏
  • 举报
回复
#!/bin/sh
echo "请输入你要查找的内容:"
read findstring
echo "请输入你要超找的路径或者文件"
read targetpath
while test -z $findstring
do
echo "输入为空请重新输入:"
read findstring
done
while test -z $targetpath
do
echo "路径或者文件为空请重新输入:"
read targetpath
done
append="/*"
if test -d $targetpath || test -f $targetpath
then
grep -l "$findstring" $targetpath$append
echo $targetpath$append
echo "grep -l '$findstring' $targetpath$append"
else
echo "不是一个文件或者路径"
fi
单引号不会变量扩展,要双引号。
向良玉 2011-10-19
  • 打赏
  • 举报
回复
问题在这
if test -d $targetpath || test -f $targetpath
应该分开目录和文件
按你的脚本文件后面会加上/* 这肯定会错的

if test -d $targetpath || test -f $targetpath
then
if test -d $targetpath
then
echo "目录"
grep -l '$findstring' $targetpath$append
fi
if test -f $targetpath
then
echo "文件"
grep -l '$findstring' $targetpath
fi
else
echo "不是一个文件或者路径"
fi
czll520 2011-10-19
  • 打赏
  • 举报
回复
谢谢各位,晚上回去试一试。分已散哈,仅有的分呀,哭..............

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧