简体   繁体   English

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

[英]in bash, heredoc inside function returns syntax error

I have the following function: 我有以下功能:

#!/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

It seems to work. 它似乎工作。 In the middle of the error message, I get my dbname , but still returns a syntax error. 在错误消息的中间,我得到我的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: `}'

If I remove the function call completely, I get the result with no errors: 如果我完全删除了函数调用,我得到的结果没有错误:

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

What do I need to do to get this to work in a function? 我需要做什么才能让它在函数中工作?

EDIT: 编辑:

Following suggestion to place bracket after EOF tag and add function keyword: 建议在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: `)' ./test.sh:第10行:`)'

Your function declaration is wrong: 你的函数声明是错误的:

get_instance{

should be one of 应该是其中之一

function get_instance {
get_instance() {

Put the close bracket on a different line: 将紧密括号放在另一条线上:

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

The terminating word of the heredoc should be the only characters on the line (except tabs when using <<- ). heredoc的终止字应该是该行上的唯一字符(使用<<-时除了制表符)。 Demo: 演示:

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

So it worked, accidentally. 所以它偶然起作用了。 Better practice is: 更好的做法是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM