0

Say I do:

ls somedir

is there a way I could re-run it with a different command?

Example:

ls somedir
<run same command as above but with cd instead of ls>
0

1 Answer 1

1

The variable $_ is the last argument of the previous line you typed. So, for example, cd $_ would do what you described

bash-4.2$ ls X
1
bash-4.2$ cd $_
bash-4.2$ ls
1

There's also some command substitution options as well; eg ^ will replace commands on the previous line

bash-4.2$ ls X
1
bash-4.2$ ^ls^cd
cd X
bash-4.2$ ls
1
5
  • Damn I should've known that, I use $_ a lot. Commented Nov 22, 2023 at 3:25
  • Also, depending on your shell editing mode... if you've done set -o emacs then <ESC>. will bring the last word in. So ls <ESC>. I'm not sure there's an equivalent in vi mode, but I could be wrong. Commented Nov 22, 2023 at 3:42
  • are there any advantages or use cases where your 2nd option would be better? So do you mean for your emacs example that if I done ls <ESC> emacs would open with the ls output written in? Commented Nov 22, 2023 at 3:51
  • No, the <ESC>. is purely a command line "insert at this point the last word". It actually shows up as if you've typed the last word. It doesn't open an editor at all. Commented Nov 22, 2023 at 3:53
  • can you give an example please? Commented Nov 22, 2023 at 5:41

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.