Cibin Joseph
Cibin Joseph

Reputation: 1273

Move and Change dir in one go

When I'm moving files from the present working directory to another directory, say 'ABC', it so happens that I usually would like to go to the directory 'ABC' immediately after the move operation. Can that be done using a single command itself?

In short, is there a 'single-command' replacement for the following:

mv foo.dat ~/Documents/ABC/
cd ~/Documents/ABC/   

I'm looking for something like this :

mv --cd foo.dat ~/Documents/ABC 

Upvotes: 0

Views: 577

Answers (2)

Mr. Llama
Mr. Llama

Reputation: 20899

You could easily make a function for it:

mvcd() {
    # Pass all of your parameters to "mv"
    mv "$@"

    # Shift down all positional parameters except the last one (which should be your destination)
    shift $(( $# - 1 ))

    if [[ -d "${1}" ]]; then
        # Change to your destination if it was a directory
        cd "${1}"

    else
        # Otherwise, assume the destination was a file name and extract its directory component
        cd "$(dirname "${1}")"
    fi
}

Using the parameter array $@ has two big advantages:

  1. You can use wildcards or globbing: mvcd *.mp3 ./old_music/
  2. You can specify additional arguments to mv: mvcd --no-clobber old.txt new.txt

Upvotes: 3

An easy function would be

If you would like to go the easy way, considering MV is already a binary included in most UNIX OS you should make a function.

For example:

mvcd()
{
    if [ -d "$2" ]; then
        mv "$1" "$2"
        cd "$2"
        echo "Moved and changed to $PWD"
    else
        mv "$1" "$2"
        echo "Moved but couldnt change path"
    fi

}

This is just an easy workaround, however you should make sure you don't call it with a second parameter being a file and not a folder, that's why I use test -d

Upvotes: 0

Related Questions