3

I'm trying to grab the last executed command, with options, and store it as a string to be written to a file. I've tried using fc but that can only give me the next to last command (for me anyways) and I've also tried !!:p which gives the right command when I type it but I can't seem to get it to work in the function itself. Can I accomplish this?

Here's what's going on. arg is what I want the string to be.

#!/bin/bash                                                                     

foo(){
    read HISTNUMVAR < histnum.txt
    TEMPHNV=$(fc -l 0 | grep -o '^[0-9]*');
    if [ $TEMPHNV -ne $HISTNUMVAR ]; then
        arg=$(***last history command here***);
        ./write_arg_to_file.sh $arg;
    fi
    echo $TEMPHNV > histnum.txt;
}

The script does everything else I need it to do besides grab the right history command.

3 Answers 3

4

There's probably a cleaner way, but you can get the previous command from history with

prev=$(fc -ln | tail -2 | head -1)
5
  • 2
    The cleaner way: fc -ln -1 avoids the invocation of head and tail. You may want to strip the leading tab and space too - reinstating a pipe. Aug 17, 2015 at 13:27
  • I've tried fc -ln -1 and it only gets the second to most recent command Aug 17, 2015 at 13:34
  • When using it as a standalone command it works but in the script it's one behind the most recent command. For example, if I enter ls and then pwd the output file will only have just got ls appended to it. Also, this omits any of the options included in the command which, ideally, I would also capture. @glenn jackman Aug 17, 2015 at 17:35
  • Well, why are you trying to re-implement bash's history mechanism? Aug 17, 2015 at 18:14
  • The motive has value but isn't something worth going through the trouble explaining. fc -ln -1 was my first attempt and, from a command line, absolutely works but didn't quite work when used in the script. Thanks for the help. Aug 17, 2015 at 20:53
2

I've managed to get something to work. From a command line, use:

history 2 | sed 's/^ *[^ ]* *//' | cut -d$'\n' -f1

From inside the script use:

arg=$(history 1 | sed 's/^ *[^ ]* *//')

This successfully saves the command and any options as a string.

0

You probably need to enable history expansion in your script, as it is disabled by default for non-interactive use. set -H should do the trick.

Untested, but I am guessing that arg="!!" will do the trick.

1
  • 1
    Could you elaborate on the set -H? Also, I tried arg="!!" and unfortunately it did not do the trick. Aug 17, 2015 at 13:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .