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

查看:113
本文介绍了如何在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]

因此,变量扩展的语义得以保留,但我无法获得提供给函数的行的确切格式.我想要的是让 echo'单引号$ VAR'产生 echo'单引号$ 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}

面对控制结构(即 if while 等),这种方法会失败.我曾考虑过使用 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天全站免登陆