How can I pass a password from a bash script to ap

2019-02-01 07:54发布

I am writing a simple bash script to install MySQL on Ubuntu.

#!/bin/bash
apt-get update

# Install MySQL5 
aptitude -y install mysql-server mysql-client libmysqlclient15-dev

However MySQL prompts for a password and confirmation. How do I pass along a root password. Is there an echo I can use?

7条回答
等我变得足够好
2楼-- · 2019-02-01 08:56

Thank you for the tip on expect. I couldn't find anything by searching Ubuntu admin forums so I went with expect. As you can see by the timestamp of this post, it took me 3 hours to get it working. Here is the code, I hope it can help someone:

#!/bin/bash
apt-get update
apt-get install expect

VAR=$(expect -c '
spawn apt-get -y install mysql-server
expect "New password for the MySQL \"root\" user:"
send "PasswordHere\r"
expect "Repeat password for the MySQL \"root\" user:"
send "PasswordHere\r"
expect eof
')

echo "$VAR"

apt-get -y install mysql-client libmysqlclient15-dev   

#For some reason important to restart - otherwise possible errors

/etc/init.d/mysql stop
/etc/init.d/mysql start
查看更多
登录 后发表回答