【问题标题】:How to get user confirmation in fish shell?如何在鱼壳中获得用户确认?
【发布时间】:2013-04-30 17:26:51
【问题描述】:

我正在尝试在 fish shellscript 中收集用户输入,尤其是以下常见形式:

This command will delete some files. Proceed (y/N)?

经过一番搜索,我仍然不确定如何干净地做到这一点。

这是在鱼身上做这件事的一种特殊方式吗?

【问题讨论】:

    标签: user-input confirmation fish


    【解决方案1】:

    我知道的最好的方法是使用内置的read。如果你在多个地方使用它,你可以创建这个辅助函数:

    function read_confirm
      while true
        read -l -P 'Do you want to continue? [y/N] ' confirm
    
        switch $confirm
          case Y y
            return 0
          case '' N n
            return 1
        end
      end
    end
    

    并在您的脚本/函数中像这样使用它:

    if read_confirm
      echo 'Do stuff'
    end
    

    查看文档了解更多选项: https://fishshell.com/docs/current/commands.html#read

    【讨论】:

    • 实际上,-p 的参数可以是任何 shell 命令,它会像你期望的那样在空格处被标记,例如echo "Delete Files? [Y/n]: "' 来自您链接的文档:“-p PROMPT_CMD 或 --prompt=PROMPT_CMD 使用 shell 命令 PROMPT_CMD 的输出作为交互模式的提示。默认提示命令是 set_color green; echo read; set_color normal; echo "> "
    • 这对我有用,但是提示暗示 Yes 是默认值,但是 switch 语句会将空解释为 No。
    • read 现在可以使用字符串而不是使用read -P "prompt: " ...read --prompt-str="prompt: " ... 的函数
    【解决方案2】:

    这与选择的答案相同,但只有一个功能,对我来说似乎更干净:

    function read_confirm
      while true
        read -p 'echo "Confirm? (y/n):"' -l confirm
    
        switch $confirm
          case Y y
            return 0
          case '' N n
            return 1
        end
      end
    end
    

    提示函数可以这样内联。

    【讨论】:

      【解决方案3】:

      这是一个带有可选默认提示的版本:

      function read_confirm --description 'Ask the user for confirmation' --argument prompt
          if test -z "$prompt"
              set prompt "Continue?"
          end 
      
          while true
              read -p 'set_color green; echo -n "$prompt [y/N]: "; set_color normal' -l confirm
      
              switch $confirm
                  case Y y 
                      return 0
                  case '' N n 
                      return 1
              end 
          end 
      end
      

      【讨论】:

        【解决方案4】:

        借助一些鱼插件fishermanget

        要安装两者,只需在您的鱼壳中即可

        curl -Lo ~/.config/fish/functions/fisher.fish --create-dirs https://git.io/fisher
        . ~/.config/fish/config.fish
        fisher get
        

        然后你可以在你的鱼函数/脚本中写这样的东西

        get --prompt="Are you sure  [yY]?:" --rule="[yY]" | read confirm
        switch $confirm
          case Y y
            # DELETE COMMAND GOES HERE
        end
        

        【讨论】:

        • 渔夫现在是fisher。不幸的是,我找不到get 去了哪里。
        • 获取包已移至github.com/fishpkg/fish-get。尽管我很喜欢fisherman 并感谢它的维护者的工作,但我不再推荐它了。它的生态系统太不稳定了,在不断追求完美的过程中,不断发生变化和被重写。
        • fish-get 似乎已经离开了那里。
        猜你喜欢
        • 1970-01-01
        • 2022-07-05
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 2014-04-24
        • 1970-01-01
        • 2022-06-20
        相关资源
        最近更新 更多