简体   繁体   English

在脚本中将带有空格的 bash 变量扩展为 arguments 到 bash function

[英]Expanding bash vars with spaces as arguments to bash function in scripts

Not critical - but I'm trying to get a deeper understanding of bash scripting and this is driving me crazy!并不重要 - 但我试图更深入地了解 bash 脚本,这让我发疯!

My goal - in a bash script:我的目标 - 在 bash 脚本中:

  • Define a function that accepts arguments定义一个接受 arguments 的 function
  • Set a bash variable (CMD) with the function name & arguments使用 function 名称和 arguments 设置 bash 变量 (CMD)
  • Execute it by $CMD通过 $CMD 执行

No problem if there is no whitespace in $args - but here's a minimal script to illustrate:如果 $args 中没有空格就没问题 - 但这里有一个最小的脚本来说明:

#!/bin/bash
function tstArgs () {
    echo "In tstArgs: ArgCnt:$#; Arg1:[$1]; Arg2:[$2]"
}
ARG1=today
ARG2=tomorrow
CMD1="tstArgs $ARG1 $ARG2"
$CMD1 #Output - As Desired: In tstArgs: ArgCnt:2; Arg1:[today]; Arg2:[tomorrow]

ARGWS1="'today with spaces'"
ARGWS2="'tomorrow with spaces'"
CMD2="tstArgs $ARGWS1 $ARGWS2"
$CMD2 #Output: In tstArgs: ArgCnt:6; Arg1:[today]; Arg2:[with]

#The dream:
ARGARR=($ARGWS1 $ARGWS2)
CMD3="tstArgs ${ARGARR[@]}"
$CMD3 #Output: In tstArgs: ArgCnt:6; Arg1:[today]; Arg2:[with]
#ETC, ETC, ETC...

This doesn't show the COUNTLESS variations I tried - single quotes, double quotes, escaping quotes, changing IFS, using parameter escape operators ${ARG1@Q} , setting args w.这没有显示我尝试过的无数变体——单引号、双引号、escaping 引号、更改 IFS、使用参数转义运算符${ARG1@Q} 、设置参数 w。 echo XXX - and so much more - way too many to include here, but to be clear, I didn't just jump on stackoverflow without first spending HOURS. echo XXX - 以及更多 - 太多了,无法包含在这里,但需要明确的是,我不是在没有先花费 HOURS 的情况下就跳上了 stackoverflow。

Weirdly, I can use params w.奇怪的是,我可以使用参数 w。 whitespace if I call the function directly:空白,如果我直接调用 function:

tstArgs $ARG1 $ARG2
#But no variation of anything like:
CMD="tstArgs $ARG1 $ARG2"
$CMD

I'm sure it must be possible, and probably simple - but it's some permutation I just haven't been able to crack.我确信这一定是可能的,而且可能很简单——但这是我无法破解的一些排列。

Of course I can work around it - but I'm stubborn & persistent & hate to give up.当然,我可以解决这个问题——但我很固执,很执着,不想放弃。 If anyone has any insight, I'd be very grateful, and maybe even finally get some sleep...如果有人有任何见识,我将不胜感激,甚至可能最终睡个好觉...

Don't put arguments in a string.不要将 arguments 放入字符串中。 Put them in an array.将它们放在一个数组中。 Array elements handle spaces much more gracefully:数组元素更优雅地处理空格:

declare -a ARGS
ARGS+=( "today with spaces" )
ARGS+=( "tomorrow with spaces" )
CMD="tstArgs"
${CMD} "${ARGS[@]}"

Alternatively:或者:

declare -a ARGS
ARGS[0]="today with spaces"
ARGS[1]="tomorrow with spaces"
CMD="tstArgs"
${CMD} "${ARGS[@]}"

Putting quotation marks around ${ARGS[@]} on the last line makes sure that each element of the array is quoted, thus preserving the spaces.在最后一行的${ARGS[@]}加上引号可确保引用数组的每个元素,从而保留空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM