ctu*_*fli 7 bash shell arguments
我正在尝试编写一个脚本,在目录中搜索模式的文件和greps.类似于下面的东西,除了 find表达式要复杂得多(排除特定的目录和文件).
#!/bin/bash
if [ -d "${!#}" ]
then
path=${!#}
else
path="."
fi
find $path -print0 | xargs -0 grep "$@"
Run Code Online (Sandbox Code Playgroud)
显然,上述方法不起作用,因为"$@"
仍然包含路径.我已经尝试通过迭代所有参数来构建参数列表的变体来排除路径,例如
args=${@%$path}
find $path -print0 | xargs -0 grep "$path"
Run Code Online (Sandbox Code Playgroud)
要么
whitespace="[[:space:]]"
args=""
for i in "${@%$path}"
do
# handle the NULL case
if [ ! "$i" ]
then
continue
# quote any arguments containing white-space
elif [[ $i =~ $whitespace ]]
then
args="$args \"$i\""
else
args="$args $i"
fi
done
find $path -print0 | xargs -0 grep --color "$args"
Run Code Online (Sandbox Code Playgroud)
但这些都是引用输入失败的.例如,
# ./find.sh -i "some quoted string"
grep: quoted: No such file or directory
grep: string: No such file or directory
Run Code Online (Sandbox Code Playgroud)
请注意,如果$@
不包含路径,则第一个脚本会执行我想要的操作.
编辑:谢谢你们的出色解决方案!我带着答案的组合:
#!/bin/bash
path="."
end=$#
if [ -d "${!#}" ]
then
path="${!#}"
end=$((end - 1))
fi
find "$path" -print0 | xargs -0 grep "${@:1:$end}"
Run Code Online (Sandbox Code Playgroud)
编辑:
原来只是稍微偏了.如果最后一个参数不是目录,则不执行删除操作.
#!/bin/bash
if [ -d "${!#}" ]
then
path="${!#}"
remove=1
else
path="."
remove=0
fi
find "$path" -print0 | xargs -0 grep "${@:1:$(($#-remove))}"
Run Code Online (Sandbox Code Playgroud)