简体   繁体   English

脚本重击和历史记录Unix

[英]Script Bash and History Unix

I just start to use Script bash on UNIX and I didn't find a solution to write the first command in the history which starts, for example, with ls. 我只是开始在UNIX上使用Script bash,但没有找到在历史记录(例如以ls开头)中编写第一个命令的解决方案。 If I write in the shell 如果我在外壳中写

history  
!ls

it works but when I'm going to create a script it won't work. 它可以工作,但是当我要创建脚本时,它将无法工作。

This is my example code 这是我的示例代码

#!/bin/bash
set -o | grep history
set -o history
#echo "HISTFILE is $HISTFILE"
#history "!ls"; 
#history
#!ls
history #it works

Another Question: Why does echo "HISTFILE is $HISTFILE" only print HISTFILE ? 另一个问题:为什么echo "HISTFILE is $HISTFILE"仅显示HISTFILE Thanks 谢谢

The shell history tools are only available in an interactive shell , so you cannot(*) put !ls into a script. 外壳程序历史记录工具仅在交互式外壳程序中可用,因此您不能(*)将!ls放入脚本中。

(*) unless you launch the script with the shell's -i option. (*),除非您使用外壳程序的-i选项启动脚本。 However, if you're writing a script with a text editor, cut-and-paste or create a function if you want to reuse commands. 但是,如果要使用文本编辑器编写脚本,则要重用命令,请剪切并粘贴或创建函数。

To get the first item in history, the following doesn't do the trick ? 要获得历史上的第一项,以下的技巧不可行吗?

echo !1

As for your second command, it should work... The HISTFILE variable may not have been correctly defined. 至于第二条命令,它应该可以工作... HISTFILE变量可能尚未正确定义。

Try to use "bash -li" instead of just "bash" in the first line of your script, to get more variables initialized. 尝试在脚本的第一行中使用“ bash -li”而不是“ bash”,以初始化更多变量。

You haven't stored anything to HISTFILE. 您尚未将任何内容存储到HISTFILE。 So it's empty. 所以它是空的。 Try this: 尝试这个:

#!/bin/bash
set -o history
ls -l 
echo "hi"
echo "hello"
HISTFILE=`history`
echo -ne "HISTFILE is: $HISTFILE"

This line: 这行:

 HISTFILE=`history`

will run the command and store the output in HISTFILE. 将运行命令并将输出存储在HISTFILE中。

The shell's history file is stored in the home directory whose path is not visible in your script. Shell的历史记录文件存储在主目录中,该主目录的路径在脚本中不可见。 So to retrieve that do: cat ~/.bash_history 所以要检索它: cat ~/.bash_history

history command stores only the last 1000 commands. history命令仅存储最后1000条命令。 So !1 gives an error then it means it's no longer available. 所以!1给出一个错误,则表示它不再可用。 So just execute history and the 1st column which gives you the number. 因此,只需执行历史记录和第一列即可获得编号。 You can only execute those commands using !NUMBER 您只能使用!NUMBER执行这些命令

like: 喜欢:

$ !50

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

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