简体   繁体   中英

How can I change to the file destination directory using a bashrc function?

I use this small function in my bashrc to quickly see the source of any custom utility that I use:

function wvi()
{
    vi `which $1`;
}

For example, fvi mysort will open the source of my utility mysort .

There is one more thing that I can use here - automatically switching to the directory that utility is present in .

For example,

~ $ which mysort
/usr/bin/mysort
~ $

then fvi mysort should do a cd /usr/bin and then open using vi .

How can I put this logic in my .basrhc ? Is there some direct utility for this, or do I need to get the path first and then chop off the last node?

dirname `which mysort`

No need for external utilities:

fvi () {
    cd "${1%/*}"
    vi "${1##*/}"
}

I'd do it this way

wvi () {(
    p=$(which "$1")
    cd "${p%/*}"
    ${EDITOR:-vi} "${p##/*/}"
)}

$EDITOR instead of literal vi thrown in just in case the user might prefer emacs (-:

wvi() {
    local file="$(which "$1")"
    cd $(dirname "$file")
    vi $(basename "$file")
    cd -  # return to the previous dir
}

You don't need the function keyword when you define your function with ()

You can write your function to operate in a subshell so you don't have to tidy up afterwards:

wvi() (
    file="$(which "$1")"
    cd $(dirname "$file")
    vi $(basename "$file")
)
cd $(dirname `which $1`)

Will work in most cases, though you may want to account for symlinks by enclosing something like

cd $(dirname $(readlink `which $1`))

if an if statement (the -h option to the test builtin looks for symlinks)

if [ -h `which $1 ]; then
  ...

The reason you may want to do this is that the behaviour of vim sometimes changes when opening symlinks, depending on what you intend to do with the file being opened.

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