How to access the last argument of a commented command

zsh

I find . (alt. for many others) to be a very useful when working in a terminal, inserting the last argument from the last line at the current prompt. However, it does not work when the last line was commented (assuming set -o interactivecomments).

I can't think of an exact use case, but it has happened several times that I've commented out a command that I realized before execution to not be what I needed at that point, and then wanted the final argument of it in a subsequent command.

I realize that there is a logic to ignoring everything commented out, since it is never interpreted and therefore none of it is tokenized into arguments, but is there any way at all to do what I want?

It would not be ideal—but would be usable—if I had to use a different keystroke, bound to an alternate command that would do what I want.

I'm using Zsh, but a Bash solution might work or be close to what I'd need to do in Zsh.

Best Answer

Don't comment the command out.

Instead, put a : at the front rather than a #. That will make your command text arguments to the null utility :, which does nothing when run. The arguments are tokenised and parsed, because it's still a command, but nothing else is done with them.


There are cases where this isn't suitable: in particular, when figuring out the command itself has side effects. A simple example is command substitution:

$ : log $(find -print -delete) --target /var/run/cache

In this case, the command inside $(...) would be run and substituted into the arguments to :, even though the original command itself would never run. A less-destructive case would be ${foo:=default} parameter expansion, which has the side effect of assigning a value to $foo.

Finally, redirections or pipes will still take place:

$ : foo > outfile
$ : bar | grep x | ...

in both cases will send empty output into the destination, which will truncate or create the file or run the subsequent commands, which may not like the empty input they get.


If you don't have any of those special concerns for your command, this is entirely safe and works in zsh, Bash, and any POSIX-compatible shell (though the alt-. behaviour afterwards won't work everywhere).

If it's specifically the last word you want, zsh provides customisable key bindings and commands that you can use to manipulate the command line. If you bindkey '^K' kill-region then you can move back to before the word, Ctrl-K to erase to the start of the line, :, and then have a safe command with just the one word you care about left.