-1

在 unix shell(特别是 Ubuntu)中有没有办法将目录更改为从 ls 命令打印的 xth 目录?我知道您可以通过多种方式对目录进行排序,但是使用 ls 的输出来获取第 x 个目录?

一个示例外壳:

$ ls
$ first_dir second_dir third_really_long_and_complex_dir

我想通过传递 3(或正确数组格式的 2)进入third_really_long_and_complex_dir。我知道我可以简单地复制和粘贴,但如果我已经在使用键盘,那么如果我知道索引,输入“cdls 2”之类的东西会更容易。

4

1 回答 1

0

交互式会话中的主要问题cd是您通常希望更改正在处理命令提示符的 shell 的当前目录。这意味着启动子shell(例如脚本)将无济于事,因为任何cd调用都不会影响父shell。

但是,根据您使用的 shell,您可能可以定义一个函数来执行此操作。例如在 bash 中:

function cdls() {
    # Save the current state of the nullglob option
    SHOPT=`shopt -p nullglob`

    # Make sure that */ expands to nothing when no directories are present
    shopt -s nullglob

    # Get a list of directories
    DIRS=(*/)

    # Restore the nullblob option state
    $SHOPT

    # cd using a zero-based index
    cd "${DIRS[$1]}"
}

ls请注意,在此示例中,出于多种原因,我绝对拒绝解析 的输出。相反,我让外壳本身检索目录列表(或目录链接)......

也就是说,我怀疑使用这个功能(或任何有这种效果的东西)是一种让自己陷入巨大混乱的好方法——比如rm在更改到错误的目录后使用。文件名自动完成已经足够危险了,不用强迫自己数数......

于 2012-11-09T16:12:10.650 回答