如何在fish shell中获取用户确认?

24

我正试图在fish shell脚本中收集用户输入,特别是以下常见形式:

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

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

在fish shell中是否有特殊的方法来做到这一点?

4个回答

36

我知道的最好方法是使用内置的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


3
实际上,-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 "> " - Ionoclast Brigham
这对我有用,但提示意味着默认情况下是“是”,然而switch语句将空值解释为“否”。 - JonoCoetzee
3
现在,使用 read -P "prompt: " ... 或者 read --prompt-str="prompt: " ...,可以将字符串传递给 read 命令,而不是一个函数。 - Brett Y

7
这段代码与选定的答案相同,只使用了一个函数,对我来说更加简洁:
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

提示功能可以内联实现,如下所示。


4
这里是一个带有可选默认提示的版本:
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

1

借助一些鱼插件 fishermanget,

要安装两个插件,只需在您的鱼壳中输入命令即可。

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

然后你可以在你的fish函数/脚本中编写类似这样的内容。
get --prompt="Are you sure  [yY]?:" --rule="[yY]" | read confirm
switch $confirm
  case Y y
    # DELETE COMMAND GOES HERE
end

1
渔夫现在是 fisher。不幸的是,我找不到 get 去了哪里。 - Raphael
get包已经迁移到https://github.com/fishpkg/fish-get。尽管我很喜欢fisherman并且感谢其维护者的工作,但我不再推荐使用它。它的生态系统非常不稳定,经常因为一些东西被重写或移动而导致频繁的变化,这是它不断追求完美的结果。 - Dennis
1
fish-get 似乎已经从那里消失了。 - Steve Bennett

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接