21

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

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

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

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

4

4 回答 4

31

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

于 2013-05-21T15:26:42.657 回答
5

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

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

提示功能可以这样内联。

于 2016-04-09T22:30:48.777 回答
2

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

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
于 2016-10-06T09:04:15.650 回答
1

在一些鱼插件渔夫的帮助下,得到

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

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
于 2017-09-25T12:43:25.647 回答