我需要在bash脚本中从终端读取一个值。我希望能够提供一个用户可以更改的默认值。
# Please enter your name: Ricardo^
在这个脚本中,提示符是“请输入您的名字:”,默认值是“Ricardo”,光标位于默认值之后。有办法在bash脚本中做到这一点吗?
我需要在bash脚本中从终端读取一个值。我希望能够提供一个用户可以更改的默认值。
# Please enter your name: Ricardo^
在这个脚本中,提示符是“请输入您的名字:”,默认值是“Ricardo”,光标位于默认值之后。有办法在bash脚本中做到这一点吗?
当前回答
我发现了这个问题,想找个方法来表达:
Something interesting happened. Proceed [Y/n/q]:
利用上面的例子,我推断出:-
echo -n "Something interesting happened. "
DEFAULT="y"
read -e -p "Proceed [Y/n/q]:" PROCEED
# adopt the default, if 'enter' given
PROCEED="${PROCEED:-${DEFAULT}}"
# change to lower case to simplify following if
PROCEED="${PROCEED,,}"
# condition for specific letter
if [ "${PROCEED}" == "q" ] ; then
echo "Quitting"
exit
# condition for non specific letter (ie anything other than q/y)
# if you want to have the active 'y' code in the last section
elif [ "${PROCEED}" != "y" ] ; then
echo "Not Proceeding"
else
echo "Proceeding"
# do proceeding code in here
fi
希望这能帮助别人,如果他们遇到同样的问题,不需要思考逻辑
其他回答
-e和-t参数不能同时使用。我尝试了一些表达式,结果是以下代码片段:
QMESSAGE="SHOULD I DO YES OR NO"
YMESSAGE="I DO"
NMESSAGE="I DO NOT"
FMESSAGE="PLEASE ENTER Y or N"
COUNTDOWN=2
DEFAULTVALUE=n
#----------------------------------------------------------------#
function REQUEST ()
{
read -n1 -t$COUNTDOWN -p "$QMESSAGE ? Y/N " INPUT
INPUT=${INPUT:-$DEFAULTVALUE}
if [ "$INPUT" = "y" -o "$INPUT" = "Y" ] ;then
echo -e "\n$YMESSAGE\n"
#COMMANDEXECUTION
elif [ "$INPUT" = "n" -o "$INPUT" = "N" ] ;then
echo -e "\n$NMESSAGE\n"
#COMMANDEXECUTION
else
echo -e "\n$FMESSAGE\n"
REQUEST
fi
}
REQUEST
我刚刚使用了我更喜欢的模式:
read name || name='(nobody)'
#Script for calculating various values in MB
echo "Please enter some input: "
read input_variable
echo $input_variable | awk '{ foo = $1 / 1024 / 1024 ; print foo "MB" }'
我发现了这个问题,想找个方法来表达:
Something interesting happened. Proceed [Y/n/q]:
利用上面的例子,我推断出:-
echo -n "Something interesting happened. "
DEFAULT="y"
read -e -p "Proceed [Y/n/q]:" PROCEED
# adopt the default, if 'enter' given
PROCEED="${PROCEED:-${DEFAULT}}"
# change to lower case to simplify following if
PROCEED="${PROCEED,,}"
# condition for specific letter
if [ "${PROCEED}" == "q" ] ; then
echo "Quitting"
exit
# condition for non specific letter (ie anything other than q/y)
# if you want to have the active 'y' code in the last section
elif [ "${PROCEED}" != "y" ] ; then
echo "Not Proceeding"
else
echo "Proceeding"
# do proceeding code in here
fi
希望这能帮助别人,如果他们遇到同样的问题,不需要思考逻辑
代码:
IN_PATH_DEFAULT="/tmp/input.txt"
read -p "Please enter IN_PATH [$IN_PATH_DEFAULT]: " IN_PATH
IN_PATH="${IN_PATH:-$IN_PATH_DEFAULT}"
OUT_PATH_DEFAULT="/tmp/output.txt"
read -p "Please enter OUT_PATH [$OUT_PATH_DEFAULT]: " OUT_PATH
OUT_PATH="${OUT_PATH:-$OUT_PATH_DEFAULT}"
echo "Input: $IN_PATH Output: $OUT_PATH"
示例运行:
Please enter IN_PATH [/tmp/input.txt]:
Please enter OUT_PATH [/tmp/output.txt]: ~/out.txt
Input: /tmp/input.txt Output: ~/out.txt