将参数中命名的变量更改为bash函数 [英] Change variable named in argument to bash function
问题描述
在我的bash脚本中,我经常提示用户输入y/n答案.由于我经常在单个脚本中多次使用此命令,因此我希望有一个函数来检查用户输入是否为Yes/No的某种变体,然后将此答案清除为"y"或"n".像这样:
In my bash scripts, I often prompt users for y/n answers. Since I often use this several times in a single script, I'd like to have a function that checks if the user input is some variant of Yes / No, and then cleans this answer to "y" or "n". Something like this:
yesno(){
temp=""
if [[ "$1" =~ ^([Yy](es|ES)?|[Nn][Oo]?)$ ]] ; then
temp=$(echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/es//g' | sed 's/no//g')
break
else
echo "$1 is not a valid answer."
fi
}
然后我想按如下方式使用该函数:
I then would like to use the function as follows:
while read -p "Do you want to do this? " confirm; do # Here the user types "YES"
yesno $confirm
done
if [[ $confirm == "y" ]]; then
[do something]
fi
基本上,我想将第一个参数的值更改为 $ confirm
的值,以便当我退出 yesno
函数时, $ confirm
是"y"或"n".
Basically, I want to change the value of the first argument to the value of $confirm
, so that when I exit the yesno
function, $confirm
is either "y" or "n".
我尝试在 yesno
函数中使用 set-"$ temp"
,但无法正常工作.
I tried using set -- "$temp"
within the yesno
function, but I can't get it to work.
推荐答案
您可以通过输出新值并覆盖调用方中的变量来做到这一点.
You could do it by outputting the new value and overwriting the variable in the caller.
yesno() {
if [[ "$1" =~ ^([Yy](es|ES)?|[Nn][Oo]?)$ ]] ; then
local answer=${1,,}
echo "${answer::1}"
else
echo "$1 is not a valid answer." >&2
echo "$1" # output the original value
return 1 # indicate failure in case the caller cares
fi
}
confirm=$(yesno "$confirm")
但是,我建议一种更直接的方法:让该函数执行提示和循环.将所有重复的逻辑移到内部.那么呼叫站点非常简单.
However, I'd recommend a more direct approach: have the function do the prompting and looping. Move all of that repeated logic inside. Then the call site is super simple.
confirm() {
local prompt=$1
local reply
while true; do
read -p "$prompt" reply
case ${reply,,} in
y*) return 0;;
n*) return 1;;
*) echo "$reply is not a valid answer." >&2;;
esac
done
}
if confirm "Do you want to do this? "; then
# Do it.
else
# Don't do it.
fi
(( $ {reply,}
是一种bash行为,将 $ reply
转换为小写.)
(${reply,,}
is a bash-ism that converts $reply
to lowercase.)
这篇关于将参数中命名的变量更改为bash函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!