4

I am using google cloud running on Ubuntu.

Every time when I upload a file I had to copy cp filename.zip ../../directory/ and I had to again type the path cd ../../directory/ to go there and unzip my file.

I need to know is there any command that I can copy and cd into that directory without typing the long directory path twice.

1
  • you can cp filename.zip ../../directory/ && cd ../../directory/
    – compiler
    Feb 13, 2018 at 6:26

2 Answers 2

7

This is not one single command, but in bash my favorite way to do that is:

$ cp filename.zip ../../directory/
$ cd :ESC: .

In the last line I mean hit Esc + .. This combination selects the last argument from the last command, in your case that's ../../directory/.

A different way to do that is:

$ cp filename.zip ../../directory/; cd $_

You can find similar commands over on stackoverflow.com: How to use arguments from previous command?.

3
  • 3
    You can also try Alt+. instead of the escape sequence.
    – Melebius
    Feb 13, 2018 at 7:33
  • 25 years of using bash and you can still learn something new about it ... Feb 13, 2018 at 7:46
  • @GeraldSchneider yup, i learned that recently as well... after many years... Feb 13, 2018 at 7:59
3

You can add this function to your .bashrc:

cpcd() { cp "$1" "$2" && cd "$2" ; }

Then, you can call cpcd with the file you want to copy as the 1st argument and the directory you want to copy/change into as the 2nd.

e.g. cpcd file.txt ~/Downloads will copy file.txt into ~/Downloads , and you'll end up in ~/Downloads as well.

You can even add ls to visually see that the file is indeed in the desired directory.

cpcd() { cp "$1" "$2" && cd "$2" && ls; }

Or, to really guarantee it...

cpcd() {
    cp "$1" "$2" && cd "$2"
    if [ -f ./"$1" ]
    then
        echo "Successfully copied '$1' into '$2'."
    fi
}
2
  • 1
    I added .bashrc file to my current directory with cpcd() { cp "$1" "$2" && cd "$2" && ls; } and use command cpcd() public.zip ../../var/ but i am getting -bash: syntax error near unexpected token public.zip any idea? Feb 13, 2018 at 6:40
  • 1
    You don't need the () after cpcd. Try cpcd public.zip ../../var/?
    – Kevin
    Feb 13, 2018 at 6:43

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