2017-03-16 199 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「$ @」是唯一正確轉發參數的版本。否則,正如另一個答案中所見,您可以操作參數並通過數組或單個字符串構造一個新列表。