History 命令在终端中工作,但在编写为 bash 脚本时不起作用 [英] History command works in a terminal, but doesn't when written as a bash script

查看:34
本文介绍了History 命令在终端中工作,但在编写为 bash 脚本时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的单行程序,可以在终端中完美运行:

I have a simple one-liner that works perfectly in the terminal:

history | sort -k2 | uniq -c --skip-fields=1 | sort -r -g | head

它的作用:给出用户最近最常用的 10 个命令.(别问我为什么要实现这样的东西)

What it does: Gives out the 10 most frequently used commands by the user recently. (Don't ask me why I would want to achieve such a thing)

我启动一个编辑器并在开头输入相同的 #!/bin/bash :

I fire up an editor and type the same with a #!/bin/bash in the beginning:

#!/bin/bash
history | sort -k2 | uniq -c --skip-fields=1 | sort -r -g | head

然后说我将它保存为 script.sh.然后,当我转到同一个终端时,输入 bash script.sh 并按 Enter,没有任何反应.

And say I save it as script.sh. Then when I go to the same terminal, type bash script.sh and hit Enter, nothing happens.

到目前为止我尝试过的:谷歌搜索.许多人有类似的痛苦,但他们通过 sudo su 或添加/删除空格得到了解决.这些都不适合我.知道我可能哪里出错了吗?

What I have tried so far: Googling. Many people have similar pains but they got resolved by a sudo su or adding/removing spaces. None of this worked for me. Any idea where I might be going wrong?

我想从终端本身执行此操作.运行此脚本的系统可能会也可能不会提供更改主文件夹中文件的权限.

I would want to do this from the terminal itself. The system on which this script would run may or may not provide permissions to change files in the home folder.

BryceAtNetwork23 提出的另一个问题,阻止我们执行它的 history 命令有什么特别之处?

Another question as suggested by BryceAtNetwork23, what is so special about the history command that prevents us from executing it?

推荐答案

查看历史记录只有在交互式 shell 中才有意义.使该命令成为一个函数而不是一个独立的脚本.在你的 ~/.bashrc 中,放

Looking at your history only makes sense in an interactive shell. Make that command a function instead of a standalone script. In your ~/.bashrc, put

popular_history() {
    history | sort -k2 | uniq -c --skip-fields=1 | sort -r -g | head
}

这篇关于History 命令在终端中工作,但在编写为 bash 脚本时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆