0

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)

3 Answers3

1

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.

target_dir=~/my_first_subfolder/my_second_subfolder/more_subfolders
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 -- "${!#}"
  else
    cd -- "$(dirname -- "${!#}")"
  fi
}
0

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 !$
SparedWhisle
  • 3,668
  • Marking this as the solution since this is the simplest answer for my case. I only need the last argument. I didn't know "!$" is a shortcut to using the last argument from the last command. If I had known something like that existed, I would've found this answer when searching on Google: https://unix.stackexchange.com/questions/88642/what-does-mean/88643 – FriskySaga Sep 16 '19 at 16:05
0

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

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

alessiosavi
  • 347
  • 2
  • 9