删除最终的bash脚本参数

问题描述:

我正在尝试编写一个脚本,用于搜索目录中的文件和greps模式。与类似,但之外的查找表达式要复杂得多(不包括特定的目录和文件)。删除最终的bash脚本参数

#!/bin/bash 
if [ -d "${!#}" ] 
then 
    path=${!#} 
else 
    path="." 
fi 

find $path -print0 | xargs -0 grep "[email protected]" 

显然,上述不起作用,因为"[email protected]"仍包含路径。我已经通过遍历所有参数排除路径,如

args=${@%$path} 
find $path -print0 | xargs -0 grep "$path" 

​​3210

试图建立一个参数列表的变种,但这些失败,并引用输入。例如,

# ./find.sh -i "some quoted string" 
grep: quoted: No such file or directory 
grep: string: No such file or directory 

注意,如果[email protected]不包含路径,第一个脚本不会做我想做的。


编辑:感谢伟大的解决方案!我去答案的组合:

#!/bin/bash 

path="." 
end=$# 

if [ -d "${!#}" ] 
then 
    path="${!#}" 
    end=$((end - 1)) 
fi 

find "$path" -print0 | xargs -0 grep "${@:1:$end}" 

编辑:

原来只是稍微偏离。如果最后一个参数不是目录,则不要执行移除操作。

#!/bin/bash 
if [ -d "${!#}" ] 
then 
    path="${!#}" 
    remove=1 
else 
    path="." 
    remove=0 
fi 

find "$path" -print0 | xargs -0 grep "${@:1:$(($#-remove))}" 
+1

这真的是优雅。 – 2010-03-16 22:20:07

+1

+1我从你的答案中学到了2件东西,并且我广泛使用了bash超过10年 – Tino 2011-10-20 02:20:35