How to use control operator after a heredoc in bash

时间:2019-05-31 11:33:07

标签: bash shell

I'm writing a bash script to create MySQL database automatically. The bash script is like the following (please ignore those variable $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. But I can not put the && after EOF, like:

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

3 个答案:

答案 0 :(得分:4)

An easy workaround is to exit if mysql fails.

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.

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

答案 1 :(得分:1)

解析很奇怪,但是可以习惯。 | && ||之后的换行符(和注释)将被忽略。因此,您只需在命令的末尾写上,但要在<< 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"

示例:

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"

示例tutorialspoint

答案 2 :(得分:0)

put sudo into round brackets:

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