在 Bash 中将目录的别名定义为 cd 的参数
Define alias for a directory as an argument to cd in Bash
我正在使用 Windows 10 Linux 子系统(Ubuntu Bash)。
我想从 Ubuntu Bash 访问我的 Windows 文件夹。
我要访问的文件夹是(注意名字中有空格):
/mnt/c/Users/some folder1/some folder2/destination - folder/
我现在在 Bash 中所做的是:
~$ cd /mnt/c/Users/some\ folder1/some\ folder2/destination\ -\ folder/
因为目录太深,不想每次都敲那么长的命令。所以我想为该文件夹定义一个别名。
在Bash中,我创建了一个文件~/.bash_aliases
。在文件 ~/.bashrc
中有以下命令:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
接下来,我想在 ~/.bash_aliases
中添加以下行:
alias mf=<the correct format of the directory>
定义好[=20=]后,我想切换到目录使用以下命令:
~$ cd mf
你能帮我解决这个问题吗?
1) <the correct format of the directory>
怎么写?
2) 我还需要做什么才能使用
~$ cd mf
如 this page 所述,"an alias is only meaningful at the beginning of a command"。所以你的别名不能作为 cd 的参数。你可以做的是
alias cdmf='cd /mnt/c/Users/some\ folder1/some\ folder2/destination\ -\ folder/'
即在您的别名中包含 cd
命令,以便键入 'cdmf' 将您带到目标目录。
要使用 cd mf
,您通常会使用符号 link(或 bash 函数),而不是别名。尝试
ln -s /mnt/c/Users/some\ folder1/some\ folder2/destination\ -\ folder/ mf
但是,这产生的 link 仅驻留在当前目录中,因此您无法从任何地方导航到目标目录。
您可以使用 bash 中提供的 cdable_vars
选项而不是别名(记录在 here 中)。要启用,请将 shopt -s cdable_vars
添加到您的 .bashrc 中,然后创建一个包含目录路径的环境变量。例如,您可以将其添加到您的 .bashrc
shopt -s cdable_vars
mydir=/really/long/dir/path
然后您就可以在 shell 中使用它,如下所示:
mike:/home/mike$ cd mydir
/really/long/dir/path
mike:/really/long/dir/path$
我正在使用 Windows 10 Linux 子系统(Ubuntu Bash)。
我想从 Ubuntu Bash 访问我的 Windows 文件夹。
我要访问的文件夹是(注意名字中有空格):
/mnt/c/Users/some folder1/some folder2/destination - folder/
我现在在 Bash 中所做的是:
~$ cd /mnt/c/Users/some\ folder1/some\ folder2/destination\ -\ folder/
因为目录太深,不想每次都敲那么长的命令。所以我想为该文件夹定义一个别名。
在Bash中,我创建了一个文件~/.bash_aliases
。在文件 ~/.bashrc
中有以下命令:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
接下来,我想在 ~/.bash_aliases
中添加以下行:
alias mf=<the correct format of the directory>
定义好[=20=]后,我想切换到目录使用以下命令:
~$ cd mf
你能帮我解决这个问题吗?
1) <the correct format of the directory>
怎么写?
2) 我还需要做什么才能使用
~$ cd mf
如 this page 所述,"an alias is only meaningful at the beginning of a command"。所以你的别名不能作为 cd 的参数。你可以做的是
alias cdmf='cd /mnt/c/Users/some\ folder1/some\ folder2/destination\ -\ folder/'
即在您的别名中包含 cd
命令,以便键入 'cdmf' 将您带到目标目录。
要使用 cd mf
,您通常会使用符号 link(或 bash 函数),而不是别名。尝试
ln -s /mnt/c/Users/some\ folder1/some\ folder2/destination\ -\ folder/ mf
但是,这产生的 link 仅驻留在当前目录中,因此您无法从任何地方导航到目标目录。
您可以使用 bash 中提供的 cdable_vars
选项而不是别名(记录在 here 中)。要启用,请将 shopt -s cdable_vars
添加到您的 .bashrc 中,然后创建一个包含目录路径的环境变量。例如,您可以将其添加到您的 .bashrc
shopt -s cdable_vars
mydir=/really/long/dir/path
然后您就可以在 shell 中使用它,如下所示:
mike:/home/mike$ cd mydir
/really/long/dir/path
mike:/really/long/dir/path$