Bash CD 直到在某个文件夹中

use*_*650 19 bash directory shell-script

我在 Magento 上做了很多工作,很多和我一起工作的人也是如此,不得不输入以下内容很烦人:

cd ../../../../../../

为了只找到你的根'httpdocs'文件夹中的几个目录,所以我试图制作一个遵循这个伪代码的脚本:

while lowest level directory != httpdocs
    cd ../
end while;
Run Code Online (Sandbox Code Playgroud)

看起来很简单,我假设我必须做某种形式的 grep 来检查当前工作目录的最后一部分是否是 httpdocs,如果不是只是继续上升直到它是真的。

我一直在考虑为此学习 bash,尽管似乎已经有一些类似的东西,而且语法让我困惑不已。

dog*_*ane 29

upto在我的 .bashrc 中调用了一个函数,它允许您按名称进入当前路径上的任何目录:

upto ()
{
    if [ -z "$1" ]; then
        return
    fi
    local upto=$1
    cd "${PWD/\/$upto\/*//$upto}"
}
Run Code Online (Sandbox Code Playgroud)

我也有这个功能的补全,这样当我点击选项卡时它会给我有效的目录名称和补全:

_upto()
{
    local cur=${COMP_WORDS[COMP_CWORD]}
    local d=${PWD//\//\ }
    COMPREPLY=( $( compgen -W "$d" -- "$cur" ) )
}
complete -F _upto upto
Run Code Online (Sandbox Code Playgroud)

此外,我还有另一个功能jd,它允许我跳转到当前目录下的任何目录:

jd(){
    if [ -z "$1" ]; then
        echo "Usage: jd [directory]";
        return 1
    else
        cd **"/$1"
    fi
}
Run Code Online (Sandbox Code Playgroud)

例子:

[/www/public_html/animals/hippopotamus/habitat/swamps/images] $ upto h[TAB][TAB]
habitat       hippopotamus
[/www/public_html/animals/hippopotamus/habitat/swamps/images] $ upto hippopotamus
[/www/public_html/animals/hippopotamus] $ jd images
[/www/public_html/animals/hippopotamus/habitat/swamps/images] $ 
Run Code Online (Sandbox Code Playgroud)

  • 这做得非常出色,我希望我能投票两次。 (2认同)

cjm*_*cjm 9

这必须是shell 函数,而不是脚本,因为脚本在新 shell 中执行(因此不能更改原始 shell 的目录)。

function cdroot()
{
  while [[ $PWD != '/' && ${PWD##*/} != 'httpdocs' ]]; do cd ..; done
}
Run Code Online (Sandbox Code Playgroud)

您当然可以随意命名该函数。

一些解释:第一个测试 ( $PWD != '/') 是一种故障保护,以防cdroot您在不在 httpdocs 文件夹中时这样做。当你到达根部时它会停止。

第二个测试 ( ${PWD##*/} != 'httpdocs') 有点复杂。 $PWD是一个包含当前目录路径的变量。${PWD##*/}修剪所有内容,包括最后一个斜杠。


cam*_*amh 6

.bashrc我能想到的最简单的 bash 函数是:

cdup() {
    cd "${PWD/\/httpdocs\/*//httpdocs}"
}
Run Code Online (Sandbox Code Playgroud)

这使用Pattern 替换参数扩展将/httpdocs/in之后的所有内容替换$PWD为 `/httpdocs'。它看起来很乱,因为我们必须转义路径中的正斜杠以将它们与 bash 扩展语法中的正斜杠区分开来。另外不要在替换字符串中转义正斜杠,所以它看起来也不一致。

如果/httpdocs/当前路径中没有,则不会执行替换,它只会更改到当前目录。

例如,替换将替换/a/b/c/httpdocs/e/f/g/a/b/c/httpdocscd进入该目录。

该函数需要在您当前的 shell 环境中(作为函数或别名),因为子进程无法更改其父进程的当前目录。这就是为什么我说把它放在你的.bashrc而不是一个 shell 脚本中。