【问题标题】:Change to xth directory terminal切换到第 x 个目录终端
【发布时间】:2012-11-09 15:37:12
【问题描述】:

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

一个示例外壳:

$ ls
$ first_dir second_dir third_really_long_and_complex_dir

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

【问题讨论】:

    标签: unix terminal ls cd


    【解决方案1】:

    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]}"
    }
    

    请注意,在此示例中,我绝对拒绝解析 lsfor a number of reasons 的输出。相反,我让外壳本身检索目录列表(或目录链接)...

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

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 2017-05-08
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多