Skip to main content

How to copy a file to a destination folder and cd to the destination folder in one command [Resolved]

To explain my question, here is the dumb way of how I'm doing things:

cp fileFromMyFriend.txt ~/my_first_subfolder/my_second_subfolder/more_subfolders
cd ~/my_first_subfolder/my_second_subfolder/more_subfolders

What is a shortcut to doing those two lines in one? I'm not looking for a concatenation symbol such as & or ;

Rather I'm trying to avoid retyping my very long folder path.

(And I already looked through the cp man page and Googled this question with different wording before coming here)

Question Credit: Friday Sky
Question Reference
Asked September 17, 2019
Posted Under: Unix Linux
3 Answers

I'm going to just answer this question of yours: Rather I'm trying to avoid retyping my very long folder path.

If that's what you are trying to do, you can just do this:

cp fileFromMyFriend.txt ~/my_first_subfolder/my_second_subfolder/more_subfolders
cd !$

credit: David Dai
Answered September 17, 2019

If this is for interactive use: type and run the first command normally. Then type cd Space M-. (you can type M-. either as Esc . or as Alt+.). The keyboard shortcut M-. (yank-last-arg) inserts the last word of the previous command.

If this is for scripting: put the directory name in a variable. Don't forget double quotes when you use the variable.

cp fileFromMyFriend.txt "$target_dir"
cd "$target_dir"

If you find that you use the same sequence of commands a lot, define a function. The bash function below calls cp and treats the last argument as a directory to change to. If the last argument is not a directory or a symbolic link to a directory, it changes to the directory containing the last argument. This works for most ways to use cp, but not with the -t option to GNU cp.

cp_cd () {
  cp "$@"
  if [ -d "${!#}/." ]; then
    cd -- "${!#}"
    cd -- "$(dirname -- "${!#}")"

credit: Gilles
Answered September 17, 2019

In order to work with the latest file you have used, you can run the following

cd $_ # directory case
vim $_ # file case

credit: alessiosavi
Answered September 17, 2019
Your Answer