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?
答案 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"
答案 2 :(得分:0)
put sudo into round brackets:
#!/bin/bash
(sudo mysql -u root << EOF
...
EOF
) && [next command]