简体   繁体   English

如何将用户输入用作历史记录

[英]How to use user input as history

I am writing a script that takes a lot of user input, then creates a file from that input. 我正在编写一个需要大量用户输入的脚本,然后根据该输入创建一个文件。 Some of the inputs are fairly repetitive, and so I would like to enable the up arrow functionality to include the strings that have already been put in. I am having difficulty finding out how to do this. 有些输入是相当重复的,因此我想启用向上箭头功能以包含已经放入的字符串。我很难找到如何执行此操作。

I have tried 我努力了

set -o history

but that only gives me the actual commands run, and not the inputs that have been received. 但这只会给我实际运行的命令,而不是已经收到的输入。 I also know that 我也知道

"\e[A" 

is the up arrow command, but this is as far as I have gotten. 是向上箭头命令,但这是我已经得到的。 A test script is as follows: 测试脚本如下:

#!/bin/bash

set -o history

read -e date
read -e date2
read -e date3

echo $date $date2 $date3

After inputting $date I would like to be able to up arrow and get the contents of $date to use for $date2 . 在输入$date我希望能够向上箭头并获取$date的内容以用于$date2 Any ideas? 有任何想法吗?

You can try to play with this little snippet: 您可以尝试使用这个小片段:

#!/bin/bash

HISTFILE=myhistoryfile
history -r
for i in {1..3}; do
   read -ep "Enter date $i: " d
   history -s "$d"
done
history -w
echo "Thanks for using this script. The history is:"
history

We define the file to be used as history file: myhistoryfile and load it into memory with history -r . 我们定义要用作历史文件的文件: myhistoryfile并将其加载到带有history -r内存中。 Then we enter the loop and after each user input in variable d we perform 然后我们进入循环,在变量d每个用户输入之后我们执行

history -s "$d"

to append the input d to current history. 将输入d附加到当前历史记录。 At the end of the loop we perform 在循环结束时,我们执行

history -w

to actually write that to the history file. 实际上将其写入历史文件。

Try different combinations: with/without history -s or history -w to understand what they really do. 尝试不同的组合:有/无history -shistory -w以了解他们真正做了什么。 And read the manual ! 阅读手册

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM