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.


    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;
    echo $TEMPHNV > histnum.txt;

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


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

prev=$(fc -ln | tail -2 | head -1)
  • 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. – Toby Speight Aug 17 '15 at 13:27
  • I've tried fc -ln -1 and it only gets the second to most recent command – Ian Panzica Aug 17 '15 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 – Ian Panzica Aug 17 '15 at 17:35
  • Well, why are you trying to re-implement bash's history mechanism? – glenn jackman Aug 17 '15 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. – Ian Panzica Aug 17 '15 at 20:53

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.


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
    Could you elaborate on the set -H? Also, I tried arg="!!" and unfortunately it did not do the trick. – Ian Panzica Aug 17 '15 at 13:43

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.