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 }
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:
Hope this helps.
3 comments
I`ll better use awk ‘{print $NF}’ instead $2.
because maybe you want to copy more file…
Thank you. You are a lifesaver. Could you please elaborate how to use this in the Bash function?
also, using $2 could make you lose files if you try to copy more files 😐