History command works in a terminal, but doesn't when written as a bash script

。_饼干妹妹 提交于 2021-02-04 06:04:33

问题


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

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

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)

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

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.

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?


Edit:

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.

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


回答1:


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
}



回答2:


To use history from a non-interactive shell, you need to enable it; it is only on by default for interactive shells. You can add the following line to the shell script:

set -o history

It still appears that only interactive shells will read the default history file by, well, default, so you'll need to populate the history list explicitly with the next line:

history -r ~/.bash_history

(Read the bash man page for more information on using a file other than the default .bash_history.)




回答3:


History command is disabled by default on bash script, that's why even history command won't work in .sh file. for its redirection. Kindly redirect bash_history file inside the .sh file.

History mechanism can be enabled also by mentioning history file and change run-time parameters as mentioned below

#!/bin/bash
HISTFILE=~/.bash_history
set -o history 

Note: mentioned above two lines on the top of the script file. Now history command will work in history.



来源:https://stackoverflow.com/questions/21762356/history-command-works-in-a-terminal-but-doesnt-when-written-as-a-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!