变量扩展向原始字符串值添加大括号

变量扩展向原始字符串值添加大括号

注意:我错过了导致此问题的脚本中的语法问题。我将 ${bar} 作为 {$bar} 传递。这可以被删除或锁定或对这些类型的问题进行任何处理。


我正在尝试测试我正在编写的脚本。为了查看变量的内容,我尝试从它传递到的函数中回显它。当它发生时,扩展变量周围会添加大括号。知道为什么要这样做以及如何防止它的指示吗?我假设如果我将变量传递给命令,它将包含大括号,这可能会导致错误。如果我的这个假设有误,请纠正我。代码是这样的:

editncopy()
{
  for i in {1..5}; do echo ${!i}; done
}

s=myserver
adir=/another/dir/
foo=/some/path/to/file.sh
bar=username@${s}:${adir}

editncopy string1 string2 ${foo} ${bar} ${s}

输出是这样的:

[me@home dir]$ ./myscript.sh
string1
string2
/some/path/to/file.sh
{username@server:/another/dir/}
myserver
[me@home dir]$

函数中总是 $4 变量添加括号({username@server:/another/dir/} 应该只是 username@server:/another/dir/)。我尝试单独回显它(echo $4),但没关系。

简而言之,该脚本将使用 sed 修改另一个脚本的内容,然后使用 scp 将其复制到其他服务器。

答案1

迭代传递给函数的参数(这也适用于迭代脚本中的参数):

#!/bin/sh

foo () {
    for i in "$@"; do
        printf 'Argument is "%s"\n' "$i"
    done
}

foo a b "c d" e "f g h"

输出:

Argument is "a"
Argument is "b"
Argument is "c d"
Argument is "e"
Argument is "f g h"

或者,根据您的价值观:

s=myserver
adir=/another/dir/
foo=/some/path/to/file.sh
bar=username@${s}:${adir}
foo string1 string2 ${foo} ${bar} ${s}

这会产生

Argument is "string1"
Argument is "string2"
Argument is "/some/path/to/file.sh"
Argument is "username@myserver:/another/dir/"
Argument is "myserver"

您的代码中可能存在拼写错误,交换了中的$和:{${bar}

$ foo {$bar}
Argument is "{username@myserver:/another/dir/}"

相关内容