【问题标题】:in bash, heredoc inside function returns syntax error在bash中,函数内部的heredoc返回语法错误
【发布时间】:2015-03-14 08:12:36
【问题描述】:

我有以下功能:

#!/bin/bash

get_instance{
dbname=$(sqlplus -s / as sysdba<<EOF
set pages 0
set feedback off
select name from v\$database;
exit;
EOF)

echo $dbname

}

get_instance

它似乎工作。在错误消息的中间,我得到了我的dbname,但仍然返回一个语法错误。

 oracle@testdb01:db01:/home/oracle/
 > ./test.sh
 ./test.sh: line 3: get_instance{: command not found
 DB01
 ./test.sh: line 11: syntax error near unexpected token `}'
 ./test.sh: line 11: `}'

如果我完全删除函数调用,我会得到没有错误的结果:

dbname=$(sqlplus -s / as sysdba<<EOF
set pages 0
set feedback off
select name from v\$database;
exit;
EOF)
echo $dbname

oracle@testdb01:db01:/home/oracle
> ./test.sh
DB01

我需要做什么才能让它在函数中工作?

编辑:

以下建议在 EOF 标记后放置括号并添加函数关键字:

 > vi test.sh
 "test.sh" 12 lines, 160 characters

#!/bin/bash
# updated file
function get_instance{
dbname=$(sqlplus -s / as sysdba<<EOF
set pages 0
set feedback off
select name from v\$database;
exit;
EOF
)
echo $dbname
}

get_instance

oracle@testdb01:db01:/home/oracle
> ./test.sh
./test.sh: line 10: syntax error near unexpected token `dbname=$(sqlplus -s / as sysdba<<EOF
set pages 0
set feedback off
select name from v\$database;
exit;
EOF
)'

./test.sh: 第 10 行:`)'

【问题讨论】:

  • 现在,我可能弄错了,但是 heredoc 不使用三个 &lt;s 吗?
  • EOF 应该单独一行,在)之前
  • @MightyPork 没有。它是 2
  • @MightyPork 不,那是别的东西(cmd &lt;&lt;&lt; "abc" 可以在 bash 中用作 echo "abc" | cmd 的替代品)
  • 是的,我从 PHP 中知道,所以我认为这将是标准语法,显然不是

标签: bash variables sqlplus heredoc solaris-10


【解决方案1】:

你的函数声明错误:

get_instance{

应该是其中之一

function get_instance {
get_instance() {

把右括号放在另一行:

dbname=$(sqlplus -s / as sysdba<<EOF
...
EOF
)

heredoc 的终止词应该是该行中唯一的字符(使用&lt;&lt;- 时的制表符除外)。演示:

$ x=$(cat <<END
> one
> two
> END)
bash: warning: here-document at line 5 delimited by end-of-file (wanted `END')
$ echo "$x"
one
two

所以它意外地起作用了。更好的做法是:

$ y=$(cat <<END
> 1
> 2
> END
> )
$ echo "$y"
1
2

【讨论】:

  • 啊,你是对的“功能”。我想知道为什么它仍然有效。该代码似乎只是跳过了有问题的行并继续。现在它还是失败了。
  • 您使用的是 Solaris 10 吗?
  • 我认为我们的系统略有不同。我用 get_instance(){} 替换了函数,并且成功了!也将 ) 放在 EOF 之后。非常感谢
  • Linux (Fedora) 上的 bash 4.2.53
  • @ndefontenay function 语法没有做任何有用的事情并且破坏了兼容性。您也可以在任何地方使用更广泛兼容的func_name() { 语法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-28
  • 2020-02-12
  • 2019-09-03
  • 1970-01-01
  • 2019-07-07
  • 2020-01-01
相关资源
最近更新 更多