user1107078
user1107078

Reputation: 455

Script Bash and History Unix

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

Upvotes: 1

Views: 758

Answers (3)

glenn jackman
glenn jackman

Reputation: 246807

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.

Upvotes: 1

P.P
P.P

Reputation: 121387

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

Upvotes: 0

Skippy Fastol
Skippy Fastol

Reputation: 1775

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.

Upvotes: 0

Related Questions