简体   繁体   English

如何在Bash中的Heredoc之后使用控件运算符

[英]How to use control operator after a heredoc in bash

I'm writing a bash script to create MySQL database automatically. 我正在编写一个bash脚本来自动创建MySQL数据库。 The bash script is like the following (please ignore those variable $db_name, $db_pwd...): bash脚本类似于以下内容(请忽略那些变量$ db_name,$ db_pwd ...):

#!/bin/bash
sudo mysql -u root << EOF
    CREATE DATABASE $db_name;
    CREATE USER $db_user IDENTIFIED BY $db_pwd;
    GRANT ALL PRIVILEGES ON $db_name.* TO $db_user;
    quit
EOF
printf "Done"

I want the database creation to be completed successfully and the print command runs afterwards. 我希望数据库创建成功完成,然后运行print命令。 But I can not put the && after EOF, like: 但是我不能将&&放在EOF之后,例如:

#!/bin/bash
sudo mysql -u root << EOF
    CREATE DATABASE $db_name;
    CREATE USER $db_user IDENTIFIED BY $db_pwd;
    GRANT ALL PRIVILEGES ON $db_name.* TO $db_user;
    quit
EOF &&
printf "Done"

It will show the error like: 它将显示如下错误:

invalid command name "EOF"
    while executing
"EOF &&"

How can I do it? 我该怎么做?

An easy workaround is to exit if mysql fails. 一个简单的解决方法是,如果mysql失败,则退出。

sudo mysql -u root << EOF || exit
    CREATE DATABASE $db_name;
    CREATE USER $db_user IDENTIFIED BY $db_pwd;
    GRANT ALL PRIVILEGES ON $db_name.* TO $db_user;
EOF
echo "Done"

Or you could add set -e to cause any failed command to immediately exit the script. 或者,您可以添加set -e导致任何失败的命令立即退出脚本。

#!/bin/bash
set -e

sudo mysql -u root << EOF
    CREATE DATABASE $db_name;
    CREATE USER $db_user IDENTIFIED BY $db_pwd;
    GRANT ALL PRIVILEGES ON $db_name.* TO $db_user;
EOF
echo "Done"

The parsing is strange, but can be used to. 解析很奇怪,但是可以习惯了。 Newlines (and comments) after | |之后的换行符(和评论) && || && || are ignored. 被忽略。 So you just write on the end of the line with the command, but after << EOF 因此,您只需在命令的末尾写上,但是在<< EOF

#!/bin/bash
sudo mysql -u root << EOF &&
    CREATE DATABASE $db_name;
    CREATE USER $db_user IDENTIFIED BY $db_pwd;
    GRANT ALL PRIVILEGES ON $db_name.* TO $db_user;
    quit
EOF
printf "Done"

Example: 例:

grep -q bla << EOF &&
bla bla
EOF
# this comment is ignored

# lines with spaces, tabs and newlines and comments only are ignored
# until the first line with something is encountered
# the following will execute only if grep returns zero status
# it can be misleading

# Because you can write a LOT here, but bash stil just sees `grep && printf`
printf "grep matched successfully"

Example at tutorialspoint . tutorialspoint的示例。

put sudo into round brackets: 将sudo放入圆括号中:

#!/bin/bash
(sudo mysql -u root << EOF
   ...
EOF
) && [next command]

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

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