在将列表转发到其他命令之前,通过某种转换(例如连接每个字符串),从本质上“映射”一个bash参数列表的最优雅方法是什么?我想到了使用xargs,但我似乎无法概念化如何做到这一点。
function do_something {
# hypothetically
for arg in "$@"; do
arg="$arg.txt"
done
command "$@"
}
do_something file1 file2 file3结果就是调用command file1.txt file2.txt file3.txt。
发布于 2017-03-16 07:07:04
您所做的大部分都是正确的,只是需要使用数组来存储新的参数:
function do_something {
array=()
for arg in "$@"; do
array+=("$arg.txt")
done
command "${array[@]}"
}
do_something file1 file2 file3发布于 2018-07-16 06:55:06
对于类似于许多函数式编程语言(如python、哈斯克尔)的python,您可以使用以下定义:
function map
{
local f="$1"
shift # consume first argument
for arg
do
"$f" "$arg" # assuming `f` prints a single line per call
done
}下面是如何在您的示例中使用它。在这里,some_cmd可能是本地定义的函数:
function do_something
{
local IFS=$'\n' # only split on newlines when word splitting
result=($(map suffix "$@")) # split into lines and store into array
some_cmd "${result[@]}" # call some_cmd with mapped arguments.
}
function suffix
{
echo "$@".txt
}
do_something file1 file2 file3下面是编写do_something的另一个变体。在这里some_cmd必须存在于$PATH中
function do_something
{
map suffix "$@" | xargs some_cmd # call some_cmd with mapped arguments.
}主要的缺点是,要在另一个函数中使用结果,需要使用IFS在新行上拆分,或者将其转换为xargs;如果映射输出包含新行,那么这两种方法都会完全失败。
发布于 2017-03-16 07:15:45
为了将参数“转发”到其他命令,有几种方法。试试这个脚本:
printargs() {
echo "Args for $1:"
shift
for a in "$@"; do
echo " arg: -$a-"
done
}
printargs dolstar $*
printargs dolstarquot "$*"
printargs dolat $@
printargs dolatquot "$@"并引用它的测试薪酬:
./sc.sh 1 2 3 多尔斯塔尔的Args: 第一条- 艺术:-2- 艺术:-3- 用于多尔斯塔的Args: 第1条2 3- 为dolat提供的Args: 第一条- 艺术:-2- 艺术:-3- 美元的Args: 第一条- 艺术:-2- 艺术:-3-
如果一个参数包含空格,情况就会有所不同:
./sc.sh 1 "2 3“ 多尔斯塔尔的Args: 第一条- 艺术:-2- 艺术:-3- 用于多尔斯塔的Args: 第1条2 3- 为dolat提供的Args: 第一条- 艺术:-2- 艺术:-3- 美元的Args: 第一条- arg:-2 3-
Dolat“$@”是唯一正确转发参数的版本。否则,如另一个答案所示,您可以通过数组或单个字符串操作参数并构造新列表。
https://stackoverflow.com/questions/42827234
复制相似问题