Ubuntu – What does !$ means in Bash scripting

bashcommand line

When reading the content of a script, I found something like:

echo "An Example" > !$

So I wonder what does !$ mean in bash .

Best Answer

From man bash (somewhere after the line 3813):

!      Start  a  history substitution, except when followed by a blank,
          newline, carriage return, = or ( (when the extglob shell  option
          is enabled using the shopt builtin).

[...]

$      The  last  word.   This  is  usually the last argument, but will
          expand to the zeroth word if there is only one word in the line.

So, the !$ will recall the last argument from the last command from history.

Here are some examples and equivalents:

$ echo foo bar
foo bar
$ echo !$ # recall the last argument from the last command from history
echo bar
bar

$ echo foo bar
foo bar
$ echo !:$ # the same like `!$'
echo bar
bar

$ echo foo bar
foo bar
$ echo !:2  # recall the second (in this case the last) argument from the last command from history
echo bar
bar

$ echo foo bar
foo bar
$ echo $_ # gives the last argument from the last command from history
bar

$ echo foo bar
foo bar
$ echo Alt+. # pressing Alt and . (dot) in the same time will automatically insert the last argument from the last command from history
bar

$ echo foo bar
foo bar
$ echo Alt+_ # the same like when you press Alt+.
bar

$ echo foo bar
foo bar
$ echo Esc. # the same like when you press Alt+.
bar

All of these will work only inside of an interactive shell. But if you use that command from your question inside of a script as you said that you sow it, then the things are different: when you run the script, this will start in a new shell, a non-interactive shell, so the history expansion doesn't has any effect in this case and so the command:

echo "An Example" > !$

creates the file !$ if not present (otherwise overwrites it) and write An Example into it.