How to get user confirmation in fish shell?

邮差的信 提交于 2019-12-20 09:39:51

问题


I'm trying to gather user input in a fish shellscript, particularly of the following oft-seen form:

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

After some searching around, I am still not sure how to do this cleanly.

Is these a special way of doing this in fish?


回答1:


The best way I know of is to use the builtin read. If you are using this in multiple places you could create this helper function:

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

and use it like this in your scripts/functions:

if read_confirm
  echo 'Do stuff'
end

See documentation for more options: https://fishshell.com/docs/current/commands.html#read




回答2:


This does the same as the chosen answer but with only one function, seems cleaner to me:

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

The prompt function can be inlined as such.




回答3:


Here's a version with optional, defaulted prompt:

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:


With the help of some fish plugins fisherman and get

To install both, simply in your fish shell

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

then you can write something like this in your fish function/script

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


来源:https://stackoverflow.com/questions/16407530/how-to-get-user-confirmation-in-fish-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!