Can't use !$ in script?

History and history expansion are disabled by default when the shell run non-interactively.

You need:

#!/bin/bash 

set -o history
set -o histexpand

ls /bin
ls !$

or:

SHELLOPTS=history:histexpand bash script.sh

it will affect all bash instances that script.sh may run.


The sane thing to do would be

ls /bin
ls $_

or

set ls /bin
$*
$*

or

c='ls /bin'
$c
$c

Caveats: it's worth remembering that each of these comes with some pitfalls. The $_ solution only captures the last single argument: so ls foo bar will leave $_ containing just bar. The one using set will override the arguments ($1, $2, etc). And all of these as written will work, but when generalized to more complex commands (where escaping and whitespace matter), you could run into some difficulties. For example: ls 'foo bar' (where the single pathname argument foo bar contains two or more spaces, or any other whitespace characters) is not going to behave correctly in either of these examples. Proper escaping (possibly combined with an eval command), or using "$@" instead of $*, might be needed to get around those cases.

Tags:

Bash