4

I'm trying to find a way to use an input file for a program in such a way that I can also use stdin.

For example, say I have a SQL script that creates a table. I invoke it like this:

mysql -p database < script.sql

This is great, but it exits out of mysql when the script is finished. Instead, I want to run other queries manually without being logged out of mysql.

I know tee can fork output to the terminal (stdout) and to a file, is there a reverse function that can be used for input, or at least a method that can be applied to most Linux/Unix commands?

1

2 Answers 2

11
cat script.sql - | mysql -p database
7
  • Do you lose the prompt with this? When I do the same with sh it reads and executes commands but I get no shell prompt. Same goes for redirecting <$(tty).
    – mikeserv
    Commented Mar 26, 2014 at 20:34
  • @mikeserv, yes, the prompts are only issued when stdin is a terminal. Here, it's a pipe. Commented Mar 26, 2014 at 20:37
  • does the same apply to mysql? I had it working by shuffling in/out around with exec at the tailend of a heredoc (which is a trick i only picked up in the first place due to some years old bash mailing list email of yours, i think), but im trying to figure on how i could do any execing if sql was the shell... Possibly that option's right out.
    – mikeserv
    Commented Mar 26, 2014 at 20:42
  • @mikeserv, there's no redirection trick that will work here. Either mysql stdin is a terminal or it's not. It has to be a terminal to get a prompt, so you'd have to have the terminal feed the content of the sql file to mysql. That could be done with the TIOCSTI ioctl under some circumstances, but it would be a lot saner to coerce mysql into reading the file before issuing a prompt. Commented Mar 26, 2014 at 20:46
  • My suspicions confirmed then. Thanks for the feedback, @Stephane.
    – mikeserv
    Commented Mar 26, 2014 at 20:47
5

I like @Stephane's answer for the general case, but here's something more appropriate for your specific example.

Start up MySQL interactive mode and use the source command to run SQL scripts.

$ mysql -p  
Enter password:  
Welcome to the MySQL monitor.  Commands end with ; or \g.  
Your MySQL connection id is 947  
Server version: 5.1.73-1 (Debian)  

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.  

mysql> source asdf.sql  
+------+  
| test |  
+------+  
| test |  
+------+  
1 row in set (0.00 sec)  

mysql> select 'cool';  
+------+  
| cool |  
+------+  
| cool |  
+------+  
1 row in set (0.00 sec)  

mysql> 

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .