2017-03-16 195 views
1

在将列表转发到某个其他命令之前,通过某种转换(例如连接每个字符串)实质上“映射”bash参数列表的最优雅方式是什么?想起使用xargs,但我似乎无法概念化如何做到这一点。bash:'map'函数参数?

function do_something { 
    # hypothetically 
    for arg in "[email protected]"; do 
     arg="$arg.txt" 
    done 

    command "[email protected]" 
} 

do_something file1 file2 file3 

这样的结果将是致电command file1.txt file2.txt file3.txt

回答

1

你所做的事是正确的大部分,只是你需要使用一个数组来存储新的论点:

function do_something { 
    array=() 
    for arg in "[email protected]"; do 
     array+=("$arg.txt") 
    done 

    command "${array[@]}" 
} 

do_something file1 file2 file3 
+1

太棒了。这肯定比[本答案](http://stackoverflow.com/a/3104637/1641160)中显示的字符串操作更具可读性(和优雅) –

0

为“前进”参数传递给其他命令,有几个方法。试试这个脚本:

printargs() { 
    echo "Args for $1:" 
    shift 
    for a in "[email protected]"; do 
    echo " arg: -$a-" 
    done 
} 

printargs dolstar $* 
printargs dolstarquot "$*" 
printargs dolat [email protected] 
printargs dolatquot "[email protected]" 

与测试aguments调用它:

./sc.sh 1 2 3
args作为dolstar:
ARG:-1-
ARG: - 2-
ARG:-3-
args作为dolstarquot:
ARG:-1 2 3-
args作为DOLAT:
ARG:-1-
ARG:-2-
ARG:-3-
args作为dolatquot:
ARG:-1-
ARG:-2-
ARG:-3-

事情去一点点不同,如果一个参数包含空格:

./sc.sh 1 “2 3”
氩为dolstar GS:
ARG:-1-
ARG:-2-
ARG:-3-
args作为dolstarquot:
ARG:-1 2 3-
args作为DOLAT:
ARG: -1-
ARG:-2-
ARG:-3-
args作为dolatquot:
ARG:-1-
ARG:-2 3-

dolatquot“$ @”是唯一正确转发参数的版本。否则,正如另一个答案中所见,您可以操作参数并通过数组或单个字符串构造一个新列表。