1

I just start to use Script bash on UNIX and I didn't find a solution to write the first command in the history which starts, for example, with ls. If I write in the shell

history  
!ls

it works but when I'm going to create a script it won't work.

This is my example code

#!/bin/bash
set -o | grep history
set -o history
#echo "HISTFILE is $HISTFILE"
#history "!ls"; 
#history
#!ls
history #it works

Another Question: Why does echo "HISTFILE is $HISTFILE" only print HISTFILE? Thanks

1
  • How do you invoke your script? Commented Apr 13, 2012 at 17:39

3 Answers 3

1

The shell history tools are only available in an interactive shell, so you cannot(*) put !ls into a script.

(*) unless you launch the script with the shell's -i option. However, if you're writing a script with a text editor, cut-and-paste or create a function if you want to reuse commands.

Sign up to request clarification or add additional context in comments.

Comments

0

To get the first item in history, the following doesn't do the trick ?

echo !1

As for your second command, it should work... The HISTFILE variable may not have been correctly defined.

Try to use "bash -li" instead of just "bash" in the first line of your script, to get more variables initialized.

Comments

0

You haven't stored anything to HISTFILE. So it's empty. Try this:

#!/bin/bash
set -o history
ls -l 
echo "hi"
echo "hello"
HISTFILE=`history`
echo -ne "HISTFILE is: $HISTFILE"

This line:

 HISTFILE=`history`

will run the command and store the output in HISTFILE.

The shell's history file is stored in the home directory whose path is not visible in your script. So to retrieve that do: cat ~/.bash_history

history command stores only the last 1000 commands. So !1 gives an error then it means it's no longer available. So just execute history and the 1st column which gives you the number. You can only execute those commands using !NUMBER

like:

$ !50

3 Comments

Hi , thanks for the answer. But i would recive the last command which begin with "ls" so didnt should i use !ls?
Isn't HISTFILE usually as a 'system' variable to indicate where the file that keeps the history is stored? i.e. HISTFILE="$HOME/.history" . @user1107078 : can you edit your question to clarify what kind of value you expect/need to be in $HISTFILE? Good luck to all.
HISTFILE is one of the system variables. Your !ls will work only in the shell. As mentioned above, you can store the history of commands executed inside the script and get it later from that variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.