Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I generally run sudo mysql database < database.dump and type the password on prompt.

In order to automate this, I tried to execute echo 'password' | sudo -S mysql database < database.dump but it is not recognizing my password.

I can sudo -S other commands normally. What might be the problem?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

No you do not

If you need to do something like this as root, please do it properly.

  • Create a new script in /usr/local/bin/ like /usr/local/bin/my_mysql_task. It'll need to be owned by root and chmod +xed. The important thing here is that nobody but root can edit it.
  • Then let your user run that script as root without a password by running sudo visudo and adding something like the following:

    username   ALL=NOPASSWD: /usr/local/bin/my_mysql_task
    

Now are you not only not piping your account password everywhere (in a way that would show in ps to most other users) but you're not piping at all, thus solving your core issue.

Never embed passwords. It's not necessary.

share|improve this answer
    
Nice solution. Just out of curiosity, do you know why my line was not working? Nice pic, btw. –  ftkg Oct 25 '13 at 19:31
    
I think Radu's probably on the right path but I'd wrap it a bit more completely: echo "password" | sudo -S sh -c "mysql database < database.dump" Edit: I can confirm that works well enough. –  Oli Oct 25 '13 at 19:35

The issue occurs because you use pipe and input redirection in the same command and in this case sudo try to read your password from database.dump file. The right way would be:

mysql_cmd="mysql database < database.dump"
echo 'password' | sudo -S $mysql_cmd

or:

alias mysql_cmd="mysql database < database.dump"
echo 'password' | sudo -S mysql_cmd

or, as Oli pointed in this comment:

echo "password" | sudo -S sh -c "mysql database < database.dump"
share|improve this answer
    
something wrong with the line: [sudo] password for user: mysql Ver 14.14 Distrib 5.5.32, for debian-linux-gnu (x86_64) using readline 6.2 [...] –  ftkg Oct 25 '13 at 19:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.