How to get second-to-last argument from previous bash command? (in an interactive bash shell)

点点圈 提交于 2019-12-04 07:33:01

Interactively, you can get the second to last argument of the previous command line with esc - 1 esc . with the default bindings.

More generally, the sequence esc . gets the final token from the previous command line, and you can pass it a numeric argument to specify a different one (for example, esc 1 esc . gets the first argument, and esc 0 esc . gets the command itself).

esc is one of the keybindings for Meta; on many modern keyboards, you can use Alt as Meta as well (you press it at the same time, not as a prefix modifier). I prefer esc as meta because when my muscle memory learned these things, we didn't have no (reliable, consistent) Alt key, and it's still portable all the way to VT100 and Sun keyboards; and at least on my current keyboard (Mac OSX Yosemite) e.g. alt-- does something else than specify a negative numeric argument.

From a previous compound command like this

echo moo; echo bar

the sequence esc 2 esc . gets the semicolon, because that's the second token.

I'm sure there is a way with ! history expansion as well, but I vastly prefer to see what I'm doing. This mechanism brings you the text you want to refer to into your current command line, so you can edit it if you like as well.

Use this to run a command using the 3rd argument of the last command in history:

echo foo > /tmp/foo &
cat !-1:3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!