将linux命令作为命令行参数传递给shell脚本

fdbelqdn  于 2023-02-13  发布在  Shell
关注(0)|答案(4)|浏览(200)

遵循命令
“查找. -类型f -正则表达式类型posix-扩展正则表达式'./ctrf.|./rbc.' -执行基本名称{} ;“
并执行它。
我将命令存储在shell脚本链接的变量中
查找命令=$1
执行
文件="$(${查找命令})”
不管用。

cyvaqqii

cyvaqqii1#

最佳实践:接受数组,而不是字符串

首先,您的shell脚本应该将运行命令 * 作为一系列独立的参数 *,而不是单个参数。

#!/usr/bin/env bash

readarray -d '' Files < <("$@")
echo "Found ${#Files[@]} files" >&2
printf ' - %q\n' "${Files[@]}"

称为:

./yourscript find . -type f -regextype posix-extended -regex './ctrf.*|./rbc.*' -printf '%f\0'

请注意,没有必要使用外部basename命令:find -printf只能直接打印文件名。

后备:将字符串正确解析为数组

如果您必须接受一个字符串,那么可以使用Reading quoted/escaped arguments correctly from a string中的答案将该字符串安全地转换为数组。
我们可以使用xargs,它牺牲了shell的完全兼容性以避免使用非标准工具:

#!/usr/bin/env bash

readarray -d '' Command_Arr < <(xargs printf '%s\0' <<<"$1")
readarray -d '' Files < <("${Command_Arr[@]}")
echo "Found ${#Files[@]} files" >&2
printf ' - %q\n' "${Files[@]}"

...脚本名为:

./yourscript $'find . -type f -regextype posix-extended -regex \'./ctrf.*|./rbc.*\' -printf \'%f\\0\''
e4eetjau

e4eetjau2#

如果要运行变量中指定的命令并将输出保存在另一个变量中,可以使用以下命令。command="find something" output=$($command)
或者,如果要将输出存储在数组中:
typeset -a output=$($command)
但是,将文件名存储在变量中,然后试图访问具有这些文件名的文件是一个坏主意,因为不可能设置正确的分隔符来分隔文件名,因为文件名可以包含除NUL之外的任何字符(请参见https://mywiki.wooledge.org/BashPitfalls)。
我不知道你想做什么,但是你的find命令包含一个错误。-exec选项必须以;来指示-exec参数的结束。除此之外,它似乎是“xy问题”参见https://xyproblem.info/如果你想获得扩展名为.ctrf或.rbc的常规文件的基本名称,请使用下面的bash脚本。
for x in **/*.+(ctrf|rbc); do basename $x ; done或zsh脚本
basename **/*.(ctrf|rbc)(#q.)
请确保您已经在shell中启用了“extendedglob”选项。要在bash中启用它,请运行以下命令。shopt -s extglob对于zsh,请运行setopt extendedglob

f5emj3cl

f5emj3cl3#

对于Find_Command,应使用数组而不是字符串:

#!/usr/bin/env bash

Find_Command=(find . -type f -regextype posix-extended -regex '(./ctrf.|./rbc.)' -exec basename {} \;)

Files=($(“${Find_Command[@]}”))

第二个语句假设文件名中没有特殊字符(如空格)。

xzabzqsa

xzabzqsa4#

使用eval

Files=$(eval "${Find_Command}")

注意保持参数的清洁和安全。

相关问题