简体   繁体   中英

Define alias for a directory as an argument to cd in Bash

I am using Windows 10 Linux Subsystem (Ubuntu Bash).

I want to access my Windows folder from Ubuntu Bash.

The folder I want to access is (note that there are spaces in the names):

/mnt/c/Users/some folder1/some folder2/destination - folder/

What I do now in Bash is:

~$ cd /mnt/c/Users/some\ folder1/some\ folder2/destination\ -\ folder/

Because the directory is too deep, I don't want to type the long command every time. So I want to define an alias for that folder.

In Bash, I created a file ~/.bash_aliases . And in the file ~/.bashrc there is following command:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

Next, I want to add the following line in ~/.bash_aliases :

alias mf=<the correct format of the directory>

After mf is defined, I want to switch to the directory using the following command:

~$ cd mf

Can you help me with this?

1) How do write the <the correct format of the directory> ?

2) What else do I need to do in order to use

~$ cd mf

Rather than alias, you can use the cdable_vars option available in bash (documented here ). To enable, add shopt -s cdable_vars to your .bashrc and then create an environment variable that contains the directory path. For example, you might add this to your .bashrc

shopt -s cdable_vars
mydir=/really/long/dir/path

and then you will be able to use this in the shell as follows:

mike:/home/mike$ cd mydir
/really/long/dir/path
mike:/really/long/dir/path$ 

As this page notes, "an alias is only meaningful at the beginning of a command". So your alias can't be an argument to cd. What you can do is

alias cdmf='cd /mnt/c/Users/some\ folder1/some\ folder2/destination\ -\ folder/'

ie including the cd command in your alias, so that typing 'cdmf' takes you to your target directory.

To use cd mf , you'd normally use a symbolic link (or a bash function), not an alias. Try

ln -s /mnt/c/Users/some\ folder1/some\ folder2/destination\ -\ folder/ mf

However, the link that this produces only resides in the current directory, so you can't navigate to your target directory from anywhere.

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