在Bash中,有没有一种方法可以将变量双引号两次扩展? [英] In Bash, is there a way to expand variables twice in double quotes?

查看:104
本文介绍了在Bash中,有没有一种方法可以将变量双引号两次扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要调试脚本,我想在每个输出的开头添加内部变量$ FUNCNAME和$ LINENO,这样我就知道输出在哪个函数和行号上出现.

For debugging my scripts, I would like to add the internal variables $FUNCNAME and $LINENO at the beginning of each of my outputs, so I know what function and line number the output occurs on.

foo(){
    local bar="something"
    echo "$FUNCNAME $LINENO: I just set bar to $bar"
}

但是由于会有许多调试输出,所以如果我可以做以下事情,它会更干净:

But since there will be many debugging outputs, it would be cleaner if I could do something like the following:

foo(){
    local trace='$FUNCNAME $LINENO'
    local bar="something"
    echo "$trace: I just set bar to $bar"
}

但是上面的字面输出: "$ FUNCNAME $ LINENO:我只是设置了某种限制" 我认为这样做是因为双引号只能在变量内一次扩展变量.

But the above literally outputs: "$FUNCNAME $LINENO: I just set bar to something" I think it does this because double quotes only expands variables inside once.

在同一行中是否有一种语法干净的方法来将变量扩展两次?

Is there a syntactically clean way to expand variables twice in the same line?

推荐答案

处理运行时数据时,您不能安全两次评估扩展.

有一些方法可以进行重新评估,但是它们需要信任您的数据-从NSA系统设计的意义上来说:受信任的组件是可以在系统发生故障时破坏系统的组件".

You cannot safely evaluate expansions twice when handling runtime data.

There are means to do re-evaluation, but they require trusting your data -- in the NSA system design sense of the word: "A trusted component is one that can break your system when it fails".

有关详细讨论,请参见 BashFAQ#48 .请记住,如果您可以记录文件名,则UNIX文件名中可以​​包含除NUL 以外的任何字符. $(rm -rf ~)'$(rm -rf ~)'.txt是法定名称. *是法定名称.

See BashFAQ #48 for a detailed discussion. Keep in mind that if you could be logging filenames, that any character except NUL can be present in a UNIX filename. $(rm -rf ~)'$(rm -rf ~)'.txt is a legal name. * is a legal name.

#!/usr/bin/env bash

trace() { echo "${FUNCNAME[1]}:${BASH_LINENO[0]}: $*" >&2; }

foo() {
        bar=baz
        trace "I just set bar to $bar"
}

foo

...当与bash 4.4.19(1)-release一起运行时,会发出:

...which, when run with bash 4.4.19(1)-release, emits:

foo:7: I just set bar to baz


请注意${BASH_LINENO[0]}${FUNCNAME[1]}的使用;这是因为BASH_LINENO的定义如下:


Note the use of ${BASH_LINENO[0]} and ${FUNCNAME[1]}; this is because BASH_LINENO is defined as follows:

一个数组变量,其成员是源文件中调用FUNCNAME的每个对应成员的行号.

An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked.

因此,FUNCNAME[0]trace,而FUNCNAME[1]foo;而BASH_LINENO[0]是调用trace的行,它是函数foo内部的行.

Thus, FUNCNAME[0] is trace, whereas FUNCNAME[1] is foo; whereas BASH_LINENO[0] is the line from which trace was called -- a line which is inside the function foo.

这篇关于在Bash中,有没有一种方法可以将变量双引号两次扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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