【问题标题】:Get current directory (without full path) in Fish Shell在 Fish Shell 中获取当前目录(没有完整路径)
【发布时间】:2015-09-23 23:55:30
【问题描述】:

我的一个朋友终于让我开始使用 Fish Shell,我正在尝试将其设置为类似于我使用 Bash 的方式。我的.bash_profile 中的PS1 列出了我所在的当前目录,然后是>。然而,它不是绝对路径(例如/Users/me/Documents/...~/Documents/...)。如果我在/Users/me/Documents/projects/Go/project1/,提示只会说project1 >

对于 Bash,是否有替代 \W 的 Fish Shell 替代品?同样,我只想要我所在的文件夹,而不是完整路径。我知道您可以使用 echo (pwd) 来完成所有这些操作。

我研究了basename 程序和echo "${PWD##*/}",但这些似乎只在 Bash 中有效。

【问题讨论】:

  • 你不能像鱼中描述的那样使用basenamedoc吗?
  • @EugeniuRosca 我试过echo (basename),得到以下结果:usage: basename string [suffix] basename [-a] [-s suffix] string [...]
  • 我查看了basename 程序 [...] 但这些似乎只在 Bash 中有效。 basename 只是一个 Unix 实用程序;它与特定的 shell 没有关联,并且应该在 Bash 和 Fish 中同样有效。
  • @Jubobs,看起来我只是没有正确格式化它。我最终使用了echo (basename $PWD),这解决了它。

标签: prompt fish


【解决方案1】:

取自@Jubobs 的回答: basename 只是一个 Unix 实用程序;它与特定的 shell 无关,并且在 Bash 和 Fish 中同样可以正常工作。

看来我在错误的上下文中使用了basename,并且没有后缀。

使用以下方法解决了这个问题:

function fish_prompt
    echo (basename $PWD) "><> "
end

【讨论】:

    【解决方案2】:

    另一种选择:fish 附带一个名为 prompt_pwd 的函数,它将 /Users/me/Documents/projects/Go/project1/ 显示为 ~/D/p/G/project1

    function fish_prompt
        echo (prompt_pwd) "><> "
    end
    

    【讨论】:

      【解决方案3】:

      prompt_pwd.fish的完整代码如下。你必须把它放在目录~/.config/fish/functions/

      function prompt_pwd --description "Print the current working directory, shortened to fit the prompt"
          set -q argv[1]
          and switch $argv[1]
              case -h --help
                  __fish_print_help prompt_pwd
                  return 0
          end
      
          # This allows overriding fish_prompt_pwd_dir_length from the outside (global or universal) without leaking it
          set -q fish_prompt_pwd_dir_length
          or set -l fish_prompt_pwd_dir_length 1
      
          # Replace $HOME with "~"
          set realhome ~
      
          # @EDITED by Thiago Andrade
          set tmpdir (basename $PWD)
          set -l tmp (string replace -r '^'"$realhome"'($|/)' '~$1' $tmpdir)
          # ORIGINAL VERSION
          # set -l tmp (string replace -r '^'"$realhome"'($|/)' '~$1' $PWD)
      
          if [ $fish_prompt_pwd_dir_length -eq 0 ]
              echo $tmp
          else
              # Shorten to at most $fish_prompt_pwd_dir_length characters per directory
              string replace -ar '(\.?[^/]{'"$fish_prompt_pwd_dir_length"'})[^/]*/' '$1/' $tmp
          end
      end
      

      然后你会看到这样的东西

      【讨论】:

      • 这个可以换成echo (basename $PWD)
      猜你喜欢
      • 2010-10-11
      • 1970-01-01
      • 2010-10-26
      • 2010-11-25
      • 1970-01-01
      • 2011-03-26
      • 2011-01-28
      相关资源
      最近更新 更多