3


I tried searching I couldn't get answer to my question, maybe because I am not sure how to ask it correctly, so I apologize in advance.
I am trying to execute chain of commands in bash script eg:

run mysql > type help > exit

root@ubuntu:# mysql
mysql> help
mysql> exit
root@ubuntu:#

How can I achieve this in bash script?

I have tried operands ||, &&, ; all this eg:

#!/bin/bash
mysql || help || exit

Didn't work. It executes commands after each other.

1
  • Do you mean you want to run a number of MySQL commands in order? Commented Dec 27, 2016 at 12:08

3 Answers 3

7

You can use a heredoc to pass some text, which the command will read as if it were a file:

mysql <<EOF
help
exit
EOF

Alternatively, in bash you can use a herestring, which achieves a similar effect to piping commands over standard input without creating any additional subshells:

mysql <<< $'help\nexit'
# or on other shells
printf 'help\nexit\n' | mysql

Note that the exit isn't really necessary, as mysql will exit when it runs out of input anyway.

Sign up to request clarification or add additional context in comments.

Comments

3

Try the following:

mysql << EOF
help
exit
EOF

This will start the mysql command then pipe the help and exit commands to mysql's stdin which is effectively the same as typing them directly

Comments

2

It sounds like what you're trying to do is run a number of MySQL commands in order.

The heredoc approach mentioned by others is the way to do in a Shell script.

Perhaps you just want to run the same MySQL commands from the command line. If so, the MySQL command line tool takes as its default argument a file containing commands such as help and other SQL commands.

  1. Create a file (Say myfile.sql) and edit contents:

    help
    select * from mytable
    
  2. Save file

  3. Pass file to mysql:

    mysql myfile.sql
    

There's no need to call exit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.