我试图聚集在鱼的shell用户输入,特别是以下经常看到的形式:如何获得用户在鱼壳中的确认?
This command will delete some files. Proceed (y/N)?
一些周围搜索后,我仍然不知道如何干净地做到这一点。
这是在鱼类中这样做的一种特殊方式吗?
我试图聚集在鱼的shell用户输入,特别是以下经常看到的形式:如何获得用户在鱼壳中的确认?
This command will delete some files. Proceed (y/N)?
一些周围搜索后,我仍然不知道如何干净地做到这一点。
这是在鱼类中这样做的一种特殊方式吗?
我知道的最好方法是使用内建的read
。不幸的是,它不能接受一个字符串,而是需要一个函数。如果您在多个地方使用这个你可以创建这个辅助功能:
function read_confirm
while true
read -l -p read_confirm_prompt confirm
switch $confirm
case Y y
return 0
case '' N n
return 1
end
end
end
function read_confirm_prompt
echo 'Do you want to continue? [y/N] '
end
,并在脚本/函数使用这样的:
if read_confirm
echo 'Do stuff'
end
有关详情,请选择文档: http://fishshell.com/docs/2.0/commands.html#read
这与选择的答案一样,但只有一个功能,对我来说似乎更清洁:
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
提示功能可以这样内联。
这里是可选的,默认的提示版本:
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
的帮助下同时安装,只需在你的鱼贝
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
实际上,'-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'>“' – 2014-07-17 23:51:36
这对我有用,但提示意味着默认是Yes,但switch语句会将空解释为No. – JonoCoetzee 2016-10-20 10:15:12
还有'read_confirm;和echo' '' – Pysis 2017-04-23 15:19:34