我尝试在 bash 脚本中格式化嵌套的 HERE 文档,但最终出现错误。由于我没有格式化任何内容,所以这有效。但为了更好的可读性,我尝试格式化以下函数。
function test_func {
: '
my test func
'
ssh -i /path/to/identity_file $TEST@${IP} << EOF
cd ~/
mkdir -p some_dir
some commands
if [ -f some_quries.sql ]
then
ssh -i /path/to/identity_file $TEST@${IP} << EOSQL
some_queries.sql; some_other_queries.sql;
exit;
EOSQL
fi
exit
EOF
当我尝试格式化时(我尝试了几个选项,但没有成功):
function test_func {
: '
my test func
'
ssh -i /path/to/identity_file $TEST@${IP} << \EOF
cd ~/
some commands
if [ -f some_quries.sql ]
then
ssh -i /path/to/identity_file $TEST@${IP} << \EOSQL
some_queries.sql; some_other_queries.sql;
exit;
EOSQL
fi
exit
EOF
我也尝试过 <<-EOF 和 <<-EOSQL,但最终得到的是第 N 行以文件结尾分隔的 here-document(需要“EOSQL”)。有人可以指导我吗?
我想我也尝试过这个:
EOSQL
fi
exit
EOF
答案1
您需要使用<<-
表格和缩进必须用制表符(而不是空格)来完成。来自man bash
:
If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.
例如给定
$ cat heredoc.sh
#!/bin/bash
cat <<EOF1
Hello from level 1
cat <<EOF2
Hello from level 2
EOF2
EOF1
然后
$ ./heredoc.sh
./heredoc.sh: line 8: warning: here-document at line 3 delimited by end-of-file (wanted `EOF1')
Hello from level 1
cat <<EOF2
Hello from level 2
EOF2
EOF1
然而
$ cat heredoc.sh
#!/bin/bash
cat <<-EOF1
Hello from level 1
cat <<-EOF2
Hello from level 2
EOF2
EOF1
然后
$ ./heredoc.sh
Hello from level 1
cat <<-EOF2
Hello from level 2
EOF2