MySQL后台查询:使用nohup执行后台查询后如何存储查询结果
Got it, let's sort this out for you! When you run a command with nohup and background it with &, the default behavior sends standard output to a file named nohup.out—but if you want more control over where your query results end up, here are three reliable methods:
1. Redirect Output Directly in the Command
The simplest way is to explicitly redirect the command's output (and error messages) to a file of your choice. Modify your original command like this:
nohup mysql -u <user> -h <host> -p<password> db_name -e "Select * from table_name;" > query_results.txt 2>&1 &
- The
> query_results.txtpart tells the shell to send all standard output (your query results) toquery_results.txt. 2>&1redirects standard error (like connection failures or SQL errors) to the same file, so you can debug issues if the query fails.
2. Use MySQL's INTO OUTFILE Clause
For more control over the output format (like CSV with custom delimiters), let MySQL handle writing the file directly. Adjust your SQL query like this:
nohup mysql -u <user> -h <host> -p<password> db_name -e "SELECT * FROM table_name INTO OUTFILE '/tmp/query_results.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n';" &
A few things to note here:
- You'll need the
FILEprivilege assigned to your MySQL user to use this. - The target path (like
/tmp/) must be writable by the MySQL server process—system temporary directories are usually safe choices. - This method lets you define exactly how the output is formatted, which is great for importing the results into other tools later.
3. Check the Default nohup.out File
If you didn't redirect output, nohup automatically saves stdout and stderr to nohup.out in your current working directory. You can view this file with:
cat nohup.out # Or follow it in real-time if the query is still running: tail -f nohup.out
Just keep in mind: running multiple nohup commands will overwrite this file, so it's better to use explicit redirection if you need to keep results long-term.
Quick Security Tip
Storing your password in plaintext in the command line is risky—it shows up in shell history and process lists. Instead, create a dedicated config file (e.g., ~/.mysql_config.cnf):
[client] user = your_username password = your_password host = your_host
Then set strict permissions on it:
chmod 600 ~/.mysql_config.cnf
And modify your nohup command to use this file:
nohup mysql --defaults-extra-file=~/.mysql_config.cnf db_name -e "Select * from table_name;" > query_results.txt 2>&1 &
This keeps your password secure while still letting you run the command in the background.
内容的提问来源于stack exchange,提问作者Jazzyb

