如何 cd 到上一个/下一个同级目录?

Est*_*eis 11 command-line shell directory cd-command

我经常有这样的项目目录布局

project
`-- component-a
|   `-- files...
`-- component-b
|   `-- files...
`-- component-c
    `-- files...
Run Code Online (Sandbox Code Playgroud)

我通常会在其中一个component目录中工作,因为文件就在那里。当我返回到 shell 时,我通常只需要移动到同级目录,尤其是当我需要对每个组件进行一些非脚本化更改时。在这些情况下,我什至不会关心我将处理的前一个同级目录是什么,或者下一个同级目录。

我可以定义一个命令prev还是next直接cd进入上一个目录或下一个目录(按字母表或其他方式)?因为一直打字cd ../com<TAB><Arrow keys>已经有点老了。

jw0*_*013 9

不要使用其他答案中的 commandlinefu 解决方案:它不安全¹ 且效率低下。² 相反,如果您正在使用bash,只需使用以下功能。要使它们持久化,请将它们放入您的.bashrc. 请注意,我使用 glob order 是因为它是内置的且简单的。尽管在大多数语言环境中,glob order 通常按字母顺序排列的。如果没有要转到的下一个或上一个目录,您将收到一条错误消息。特别是,如果您尝试nextprev在根目录/.

## bash and zsh only!
# functions to cd to the next or previous sibling directory, in glob order

prev () {
    # default to current directory if no previous
    local prevdir="./"
    local cwd=${PWD##*/}
    if [[ -z $cwd ]]; then
        # $PWD must be /
        echo 'No previous directory.' >&2
        return 1
    fi
    for x in ../*/; do
        if [[ ${x#../} == ${cwd}/ ]]; then
            # found cwd
            if [[ $prevdir == ./ ]]; then
                echo 'No previous directory.' >&2
                return 1
            fi
            cd "$prevdir"
            return
        fi
        if [[ -d $x ]]; then
            prevdir=$x
        fi
    done
    # Should never get here.
    echo 'Directory not changed.' >&2
    return 1
}

next () {
    local foundcwd=
    local cwd=${PWD##*/}
    if [[ -z $cwd ]]; then
        # $PWD must be /
        echo 'No next directory.' >&2
        return 1
    fi
    for x in ../*/; do
        if [[ -n $foundcwd ]]; then
            if [[ -d $x ]]; then
                cd "$x"
                return
            fi
        elif [[ ${x#../} == ${cwd}/ ]]; then
            foundcwd=1
        fi
    done
    echo 'No next directory.' >&2
    return 1
}
Run Code Online (Sandbox Code Playgroud)

¹ 它不处理所有可能的目录名称。 解析ls输出从来都不是安全的

²cd可能不需要非常高效,但是 6 个进程有点过多。