如何在鱼壳中获得用户确认?

use*_*584 12 user-input confirmation fish

我正在尝试收集鱼类shellcript中的用户输入,特别是以下常见形式的用户输入:

This command will delete some files. Proceed (y/N)?
Run Code Online (Sandbox Code Playgroud)

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

这是鱼的特殊方式吗?

ter*_*rje 22

我所知道的最好的方法是使用内置的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
Run Code Online (Sandbox Code Playgroud)

并在脚本/函数中使用它:

if read_confirm
  echo 'Do stuff'
end
Run Code Online (Sandbox Code Playgroud)

有关更多选项,请参阅文档:https : //fishshell.com/docs/current/commands.html#read

  • 实际上,`-p`的参数可以是任何shell命令,它会像你在空格处所期望的那样被标记化,例如`echo'删除文件?[Y/n]:"'`来自您链接的文档:" - p PROMPT_CMD或--prompt = PROMPT_CMD使用shell命令PROMPT_CMD的输出作为交互模式的提示.默认的提示命令是`set_color green; echo read; set_color normal; echo">"` (3认同)
  • read现在可以使用`read -P'提示字符串而不是函数:"...`或`read --prompt-str ="提示符:"...` (3认同)

小智 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
Run Code Online (Sandbox Code Playgroud)

提示函数可以这样内联。