bash 在一个命令中创建临时文件并将输出重定向到它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40414570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:22:03  来源:igfitidea点击:

Create temporary file and redirect output to it in one command

bashshellunix

提问by Travis Clarke

I designed a custom script to grep a concatenated list of .bash_historybackup files. In my script, I am creating a temporary file with mktempand saving it to a variable temp. Next, I am redirecting output to that file using the catcommand.

我设计了一个自定义脚本来 grep.bash_history备份文件的连接列表。在我的脚本中,我正在创建一个临时文件mktemp并将其保存到变量temp. 接下来,我使用cat命令将输出重定向到该文件。

Is there a means to create a temporary file (using mktemp), redirect output to it, then store it in a variable in one command, while preserving newline characters?

有没有办法创建一个临时文件(使用mktemp),将输出重定向到它,然后在一个命令中将它存储在一个变量中,同时保留换行符?

The below snippet of code works just fine, but I have a feeling there is a more terse and canonical way to achieve this in one line – maybe using process substitutionor something of the like.

下面的代码片段工作得很好,但我觉得有一种更简洁、更规范的方法可以在一行中实现这一点——可能使用进程替换或类似的方法。

# Concatenate all .bash_history files into a temporary file `temp`.
temp="$(mktemp)"
cat "$HOME/.bash_history."* > $temp
trap 'rm -f $temp' 0

# Set `HISTFILE` shell variable to the `temp` file.
HISTFILE="$temp"

keyword=""

# Search for `keyword` using the `history` command
if [[ "$keyword" ]]; then
    # Enable history
    set -o history

    history | grep "$keyword"

    # Disable history
    set +o history
else
    echo -e "usage: search <keyword>"
    exit 0
fi

回答by Charles Duffy

If you're comfortable with the side effect of making the assignment conditional on tempfilenot previously having a nonempty value, this is straightforward via the ${var:=value}expansion:

如果您对使赋值以tempfile先前没有非空值为条件的副作用感到满意,那么通过${var:=value}扩展可以很简单:

cat "$HOME/.bash_history" >"${tempfile:=$(mktemp)}"

回答by artdanil

I guess there is more than one way to do it. I found following to be working for me:

我想有不止一种方法可以做到这一点。我发现以下对我有用:

cat myfile.txt > $(echo "$(mktemp)")

Also don't forget about tee:

也不要忘记tee

cat myfile.txt | tee "$(mktemp)" > /dev/null