1

I'm still quite new to bash scripting and I need a very simple script that, if there is command history, displays it, and, if there isn't, informs the user that there is no command history.

What I have so far is this:

#!/bin/bash

if [ -n "$(history)" ]
    then
        history
    else
        echo "No entered commands."
fi

But, no matter whether the history has or hasn't been cleared with history -c, the above script returns:

/path/to/script.sh: 3: history: not found
No entered commands.

What exactly is going wrong and how can I adapt or rewrite this script to work?

2
  • @Hannu Isn't that second/closing quotation mark meant to be between the ) and the -gt, i.e. the line should read if [ "$(history | wc -l)" -gt 0 ]? Regardless, I'm getting history: not found on lines 3 and 5 using your suggestion and my amendment. – saalkom Dec 1 '19 at 8:52
  • Yes, sorry... I rewrote all this in the answer below... will correct that. Done. – Hannu Dec 1 '19 at 8:54
1

if [ "$(history | wc -l)" -gt 0 ] ..., see man bash under CONDITIONAL EXPRESSIONS, [ is the same as test so man test will tell more about that.

NOT CHECKED FACT: (from memory!)
Now, please note that launching a bash script does its magic by starting a new "bash" (the executable); this leads to the fact that the history in that bash session (while the script is running) will be something else than what you have in the session where you launched the script.

To be able to check the history in the CURRENT session, you will have to do it differently:
One way is to make your "script" be a bash function, e.g. in $HOME/.bashrc and then use the function.
Alternatively, place the function in a separate file and source scriptfile.sh to make it appear and run in the current bash session.

MORE:
The fact that you start the script will be recorded in history. I'm not sure you will ever have less than one line in history, when the script is running.

1
  • Turns out history wasn't found was because the script (of which this snippet of code was just the beginnings of a small part thereof) was running in a noninteractive shell (via a launcher that executes xfce4-terminal -H -x /path/to/script.sh). I didn't try the .bashrc method but source-ing the script as a separate file still didn't work, due to the noninteractive shell. HISTFILE=~/.bash_history; set -o history returned an illegal operation error. I know it's not the same, but my script now uses cat -n $HOME/.bash_history instead of history, which is better for my purposes anyway. – saalkom Dec 1 '19 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.