Home Bash Tips [Bash Tips] How to cp or mv and cd in one command

[Bash Tips] How to cp or mv and cd in one command

By sk
Published: Last Updated on 5.1K views

The other day we learned how to cd and ls in one command. Today we will see yet another cool Bash tip - cp or mv and cd in one command. Meaning - we are going to copy or move files/directories from one location to another and cd into the destination directory instantly. Of course we can do this with an one-liner command. For example, it is possible to copy or move files/directories to another directory and cd into the destination directory using command:

cp source destination && cd destination

Or,

mv source destination && cd destination

However, we are not going to do it now. We use a simple bash function to combine cp or mv command and cd command and run it as a single command. This trick should work on all Unix-like systems that supports BASH.

How to cp or mv and cd in one command

Open your ~/.bashrc file in your favorite editor:

$ nano ~/.bashrc

Add the following lines at the end:

#cp and cd in one command
cpcd (){
  if [ -d "$2" ];then
    cp $1 $2 && cd $2
  else
    cp $1 $2
  fi
}

#mv and cd in one command
mvcd (){
  if [ -d "$2" ];then
    mv $1 $2 && cd $2
  else
    mv $1 $2
  fi
}
Bash function to cp or mv and cd in one command
Bash function to cp or mv and cd in one command

Save and close the file. Run the following command to take effect the changes.

$ source ~/.bashrc

Now copy or move files/directories from one location to another and you will automatically be landed in the destination location.

Let us make some sample directories and files.

$ mkdir dir1 dir2
$ touch file1 file2

Now copy the file1 to dir1 using command:

$ cpcd file1 dir1
$ pwd
/home/sk/dir1

As you see, the above command copies the file1 to dir1 and then automatically cd into the dir1 location.

Next move file2 to dir2 using command:

$ cd
$ mvcd file2 dir2
$ pwd
/home/sk/dir2

This command copies file2 to dir2 and it automatically cd into the dir2 location.

Sample output:

cp or mv and cd in one command
cp or mv and cd in one command

Hope this helps.

You May Also Like

3 comments

Florin Idita April 12, 2020 - 1:37 pm

I`ll better use awk ‘{print $NF}’ instead $2.
because maybe you want to copy more file…

Reply
sk April 12, 2020 - 2:15 pm

Thank you. You are a lifesaver. Could you please elaborate how to use this in the Bash function?

Reply
Florin Idita April 12, 2020 - 1:39 pm

also, using $2 could make you lose files if you try to copy more files 😐

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. Accept Read More