在 shell 中为实用程序构建参数的可移植方法?
Portable way to build up arguments for a utility in shell?
我正在编写一个 shell 脚本,旨在 运行 在一系列机器上。其中一些机器有 bash 2 或 bash 3。有些是 运行ning BusyBox 1.18.4,其中 bin/bash
存在但
/bin/bash --version
return 什么都没有
foo=( "hello" "world" )
抱怨接近意外 "("
的语法错误,无论是否有括号内的额外空格......所以数组似乎有限或缺失
还有更现代或更全功能的 Linux 和 bash 版本。
bash 脚本在 运行 时构建参数以调用 find
等实用程序的最便携方式是什么?我可以建立一个字符串,但觉得数组是更好的选择。除了上面的第二个要点...
假设我的脚本是 foo
,您可以这样称呼它:foo -o 1 .jpg .png
这是一些伪代码
#!/bin/bash
# handle option -o here
shift $(expr $OPTIND - 1)
# build up parameters for find here
parameters=(my-diretory -type f -maxdepth 2)
if [ -n "" ]; then
parameters+=-iname '*' -print
shift
fi
while [ $# -gt 0 ]; do
parameters+=-o -iname '*' -print
shift
done
find <new positional parameters here> | some-while-loop
如果您需要使用 mostly-POSIX sh,例如在 busybox ash-named-bash 中可用,您可以直接使用 set
[ 构建位置参数=14=]
$ set -- hello
$ set -- "$@" world
$ printf '%s\n' "$@"
hello
world
举个更贴切的例子:
$ set -- /etc -name '*b*'
$ set -- "$@" -type l -exec readlink {} +
$ find "$@"
/proc/mounts
虽然您的问题不仅仅涉及 Bash,但阅读 Wooledge Bash 关于该主题的常见问题解答可能会让您受益:
http://mywiki.wooledge.org/BashFAQ/050
它提到了 "set --" 用于较旧的 shell,但也提供了很多背景信息。在构建参数列表时,很容易创建一个在简单情况下工作但在数据具有特殊字符时失败的系统,因此阅读该主题可能是值得的。
我正在编写一个 shell 脚本,旨在 运行 在一系列机器上。其中一些机器有 bash 2 或 bash 3。有些是 运行ning BusyBox 1.18.4,其中 bin/bash
存在但
/bin/bash --version
return 什么都没有foo=( "hello" "world" )
抱怨接近意外"("
的语法错误,无论是否有括号内的额外空格......所以数组似乎有限或缺失
还有更现代或更全功能的 Linux 和 bash 版本。
bash 脚本在 运行 时构建参数以调用 find
等实用程序的最便携方式是什么?我可以建立一个字符串,但觉得数组是更好的选择。除了上面的第二个要点...
假设我的脚本是 foo
,您可以这样称呼它:foo -o 1 .jpg .png
这是一些伪代码
#!/bin/bash
# handle option -o here
shift $(expr $OPTIND - 1)
# build up parameters for find here
parameters=(my-diretory -type f -maxdepth 2)
if [ -n "" ]; then
parameters+=-iname '*' -print
shift
fi
while [ $# -gt 0 ]; do
parameters+=-o -iname '*' -print
shift
done
find <new positional parameters here> | some-while-loop
如果您需要使用 mostly-POSIX sh,例如在 busybox ash-named-bash 中可用,您可以直接使用 set
[ 构建位置参数=14=]
$ set -- hello
$ set -- "$@" world
$ printf '%s\n' "$@"
hello
world
举个更贴切的例子:
$ set -- /etc -name '*b*'
$ set -- "$@" -type l -exec readlink {} +
$ find "$@"
/proc/mounts
虽然您的问题不仅仅涉及 Bash,但阅读 Wooledge Bash 关于该主题的常见问题解答可能会让您受益:
http://mywiki.wooledge.org/BashFAQ/050
它提到了 "set --" 用于较旧的 shell,但也提供了很多背景信息。在构建参数列表时,很容易创建一个在简单情况下工作但在数据具有特殊字符时失败的系统,因此阅读该主题可能是值得的。