user
user

Reputation: 3456

Can I reference the last path or file I specified in bash?

For example, if I mv a file to say, example.ex, and then want to chmod it, is there a way I can quickly access example.ex?

I would expect something along the lines of a $last or $-1 but my search for "Bash reference last file|path" yields unrelated things.

Upvotes: 2

Views: 173

Answers (2)

Marian
Marian

Reputation: 6257

For interactive use, there is a keyboard combination for exactly this: alt+. (alt+dot)

It directly inserts the last argument of the last command in your command line (if you press it multiple times, you cycle the last argument of each of the commands before).

Try it, I got accustomated to this and I use it a looot now.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881403

$_ will give you the last word of the previous command which seems to be enough for your current needs. For example:

mkdir biglongdirname
cp *.c $_

will make that directory and copy all your C files into it.

For your specific example, it would be something like:

mv srcfile.ex example.ex
chmod 700 $_

Note that $_ is the last argument after expansion, you can use the csh-like variant !$ to get the last argument before expansion (the comments were added by me after the event):

pax> echo {1..5}  # will expand to "1 2 3 4 5" (sans quotes).
1 2 3 4 5

pax> echo !$      # will give pre-expansion last arg "{1..5}".
echo {1..5}       # shows command before executing.
1 2 3 4 5

pax> echo $_      # will give post-expansion last arg "5".
5

Upvotes: 4

Related Questions