2

I don't know if there's a command for this, but when I'm working in terminal, I often find myself moving a file to a directory, and then wanting to cd there. For example

mv Keasbey\ Nights /media/ipod/Music/Catch\ 22

cd /media/ipod/Music/Catch\ 22

It's a pain to have to type this second part all the time. Is there an easy way to do this automatically in bash? I know that

cd-

will take me to my last directory, but this isn't really what I'm looking for. In my example I haven't been to /media/ipod/Music/Catch\ 22 yet.

4 Answers 4

3

If you hold down your alt key and press ".", the shell will automatically type the last argument to the last command you entered. In your situation, for the 2nd command, type "cd ", press alt-., and the rest should happen on its own.

3
  • This is exactly what I wanted. Out of curiosity, is there a way to get the second to last argument?
    – Wilduck
    Dec 14, 2009 at 4:22
  • I don't know. I am a bash newbie. I would kind of like to know the answer to that myself, but not badly enough to ask that question here. Dec 14, 2009 at 4:31
  • You can't trivially get the second-to-last argument, unless you know exactly how many arguments there are, in which case you can use e.g. !!:4 for the fourth argument. Dec 14, 2009 at 5:06
3

You want to use !$, which expands to the last word used in the previous command:

computer:~ zac$ mkdir My\ Subdir
computer:~ zac$ cd !$
cd My\ Subdir
computer:~/My Subdir zac$

See the man page for bash, under HISTORY EXPANSION, Word Designators.

Also see !*, which expands to all but the first word.

2

You could also make a function (place this in your ~/.bashrc):

function mvcd ()
{
 mv "$1" "$2"
 cd "$2"
}

you use it with the same arguments as mv, except you will be in that directory after executing the command.

example:

[john@awesome ~]# touch file
[john@awesome ~]# mkdir some_folder
[john@awesome ~]# mvcd file some_folder/
[john@awesome some_folder]# ls
file
[john@awesome some_folder]# pwd
/home/john/some_folder
2

To get the next-to-last argument:

Alt-- (alt-minus) followed by Ctrl-Alt-y

That's "digit-argument (negative)" followed by "yank-nth-arg". See man readline for more information.

You could type digits after the alt-minus to get preceding arguments.

To get arguments counting from the beginning:

Alt-0 is the command

Alt-1 is the first argument

etc., followed by Ctrl-Alt-y

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .