You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL后台查询:使用nohup执行后台查询后如何存储查询结果

How to Save MySQL Query Results When Running with 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.txt part tells the shell to send all standard output (your query results) to query_results.txt.
  • 2>&1 redirects 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 FILE privilege 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 23:37:34