Bash – How to run one command with a directory as argument, then cd to the same? I get “no such file or directory”

bashcd-command

I would like to construct a short function to do the following. Let's say that I move file 'file.tex' to my documents directory:

mv file.tex ~/Documents

Then, I'd like to cd to that directory:

cd ~/Documents

I'd like to generalize this to any directory, so that I can do this:

mv file.tex ~/Documents
follow

and have the follow command read the destination from the previous command, then execute accordingly. For a simple directory, this doesn't save much time, but when working with nested directories, it would be tremendous to be able to just use

mv file.tex ~/Documents/folder1/subfolder1
follow

I thought it would be relatively simple, and that I could do something like this:

follow()
{
    place=`history 2 | sed -n '1p;1q' | rev | cut -d ' ' -f1 | rev`
    cd $place
}

but this doesn't seem to work. If I echo $place, I do get the desired string (I'm testing it with ~/Documents), but the last command returns

No such file or directory

The directory certainly exists. I'm at a loss. Could you help me out?

Best Answer

Instead of defining a function, you can use the variable $_, which is expanded to the last argument of the previous command by bash. So use:

cd "$_"

after mv command.

You can use history expansion too:

cd !:$

If you must use a function:

follow () { cd "$_" ;}

$ follow () { cd "$_" ;}
$ mv foo.sh 'foo bar'
$ follow 
foo bar$ 

N.B: This answer is targeted to the exact command line arguments format you have used as we are dealing with positional parameters. For other formats e.g. mv -t foo bar.txt, you need to incorporate specific checkings beforehand, a wrapper would be appropriate then.

Related Question