简体   繁体   中英

Bash alias for 'move a file to a directory, and then go to that directory'

So say I have a file in my home dir ~/ :

sample.txt 

and I want to move it to ~/work/

I would do mv sample.txt work/ and it would work.

But what if I want an alias that would mv the file, and then cd to the last arg? This means to move the file to a folder, and then automatically cd into that folder.

I have something like this (note that my mv is aliased for default overwrite protection, not sure if that's the issue):

alias mv='mv -i $@'
alias mvg='mv "$@"; cd !$;'

It doesn't work (seems like the mv isn't getting the args).

Any help will be appreciated!

Rather than using an alias, you could define a simple function:

mv_cd() { mv "$1" "$2" && cd "$2"; }

Usage: mv_cd file dest

That only works for one file. To allow multiple files, you could do something like this:

mv_cd() { 
    declare -a files
    while (($# > 1)); do 
        files+=("$1")
        shift
    done
    mv "${files[@]}" "$1" && cd "$1"
}

Usage: mv_cd file1 file2 ... fileN dest

This builds an array containing all of the file names that are passed to the function, then moves them and changes directory.

As mentioned in the comments (thanks @chepner), it's unnecessary to build an array inside the function. Instead, you can use array slicing to separate the last argument from the others:

mv_cd() { mv "${@:1:$#-1}" "${@: -1}" && cd "${@: -1}"; }

The arguments passed to the function are in the array $@ . ${@:1:$#-1} is a slice from the first element to the $#-1 th element, where $# is the length of the array. Negative indices can be used to specify a range from the end of the array, so ${@: -1} gets the last element of the array. There's no need to specify the end of the range, as it goes to the end of the array by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM