历史命令在终端中有效,但作为bash脚本编写时无效 [英] History command works in a terminal, but doesn't when written as a bash script

查看:62
本文介绍了历史命令在终端中有效,但作为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?

推荐答案

仅在交互式外壳中查看历史记录才有意义.使该命令成为函数而不是独立脚本.在您的〜/.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
}

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

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