Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...