在bash中,heredoc inside函数返回语法错误

时间:2015-01-15 19:51:03

标签: bash variables sqlplus heredoc solaris-10

我有以下功能:

#!/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:line 10:`)&#39;

1 个答案:

答案 0 :(得分:4)

您的函数声明错误:

get_instance{

应该是

之一
function get_instance {
get_instance() {

将近距离括号放在另一行:

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

heredoc的终止字应该是该行上的唯一字符(使用<<-时的选项卡除外)。演示:

$ 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