2013-05-06 53 views
8

我試圖聚集在魚的shell用戶輸入,特別是以下經常看到的形式:如何獲得用戶在魚殼中的確認?

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

一些周圍搜索後,我仍然不知道如何幹淨地做到這一點。

這是在魚類中這樣做的一種特殊方式嗎?

回答

14

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

+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'>「' – 2014-07-17 23:51:36

+0

這對我有用,但提示意味着默認是Yes,但switch語句會將空解釋爲No. – JonoCoetzee 2016-10-20 10:15:12

+0

還有'read_confirm;和echo' '' – Pysis 2017-04-23 15:19:34

4

這與選擇的答案一樣,但只有一個功能,對我來說似乎更清潔:

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 

提示功能可以這樣內聯。

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 
1

隨着一些魚插件fishermanget

的幫助下同時安裝,只需在你的魚貝

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