如何在bash函数参数中引用? [英] How to quotes in bash function parameters?

查看:30
本文介绍了如何在bash函数参数中引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是将一行可能包含引号(单引号或双引号)的行作为函数的输入,并完全按照提供给函数的方式回显该行.例如:

What I'd like to do is take, as an input to a function, a line that may include quotes (single or double) and echo that line exactly as it was provided to the function. For instance:

function doit {
   printf "%s " ${@} 
   eval "${@}"
   printf " # [%3d]\n" ${?}
}

给定以下输入

doit VAR=42
doit echo 'single quote $VAR'
doit echo "double quote $VAR"

产生以下内容:

VAR=42  # [  0]
echo single quote $VAR  # [  0]
echo double quote 42  # [  0]

因此,变量扩展的语义按我的预期保留了下来,但是我无法获得提供给函数的行的确切格式.我想要的是 doit echo 'single quote $VAR' 结果 echo 'single quote $VAR'.

So the semantics of the variable expansion are preserved as I'd expect, but I can not get the exact format of the line as it was provided to the function. What I'd like is to have doit echo 'single quote $VAR' result in echo 'single quote $VAR'.

我确定这与 bash 在将参数传递给函数之前处理参数有关;我只是在寻找解决方法(如果可能的话).

I'm sure this has to do with bash processing the arguments before they are passed to the function; I'm just looking for a way around that (if possible).

因此,我的意图是在提供执行的精确副本的同时隐藏脚本的执行,该副本可用作诊断工具,包括每个步骤的退出状态.

So what I had intended was to shadow the execution of a script while providing an exact replica of the execution that could be used as a diagnostic tool including exit status of each step.

虽然我可以通过做类似的事情来获得上述所需的行为

While I can get the desired behavior described above by doing something like

while read line ; do 
   doit ${line}
done < ${INPUT}

这种方法在面对控制结构(即 ifwhile 等)时失败了.我想过使用 set -x 但这也有它的局限性: " 变成 ' 并且退出状态对于失败的命令不可见.

That approach fails in the face of control structures (i.e. if, while, etc). I thought about using set -x but that has it's limitations as well: " becomes ' and exit status is not visible for commands that fail.

推荐答案

发生这种情况的原因是因为 bash 会按照您的想法解释参数.当它调用函数时,引号根本就不存在了,所以这是不可能的.它在 DOS 中有效,因为程序可以自己解释命令行,而不是它对您有帮助!

The reason this happens is because bash interprets the arguments, as you thought. The quotes simply aren't there any more when it calls the function, so this isn't possible. It worked in DOS because programs could interpret the command line themselves, not that it helps you!

这篇关于如何在bash函数参数中引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆