【问题标题】:Removing final bash script argument删除最终的 bash 脚本参数
【发布时间】:2011-01-28 08:18:01
【问题描述】:

我正在尝试编写一个脚本来搜索目录中的文件和 greps 模式。类似于下面的除了,查找表达式要复杂得多(不包括特定的目录和文件)。

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

find $path -print0 | xargs -0 grep "$@"

显然,上述方法不起作用,因为"$@" 仍然包含路径。我尝试了通过迭代所有参数以排除路径来构建参数列表的变体,例如

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

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"

但这些因引用输入而失败。例如,

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

请注意,如果$@ 不包含路径,则第一个脚本会执行我想要的操作。


编辑:感谢您提供出色的解决方案!我结合了答案:

#!/bin/bash

path="."
end=$#

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

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

【问题讨论】:

    标签: bash shell arguments


    【解决方案1】:

    编辑:

    原版只是略有偏差。如果最后一个参数不是目录,则不会删除。

    #!/bin/bash
    if [ -d "${!#}" ]
    then
        path="${!#}"
        remove=1
    else
        path="."
        remove=0
    fi
    
    find "$path" -print0 | xargs -0 grep "${@:1:$(($#-remove))}"
    

    【讨论】:

    • +1 我从您的回答中学到了 2 件事,并且我广泛使用 bash 超过 10 年
    猜你喜欢
    • 2013-12-22
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 2020-12-31
    相关资源
    最近更新 更多