为何bash中read -p仅能正确读取第一个变量?
问题描述
我通过教程了解到使用read -p可将用户输入保存为变量,于是编写了一段类似Madlibs的测试脚本,希望能多次将用户输入转为变量后输出。脚本示例如下:
read -p "What is your favorite fruit?" fruit echo Oh, I see... sleep 2s read -p "And what is your mama's name?" mama echo Amazing... sleep2s read -p "And how many years have you been a little bitch?" years echo Understood... sleep 2s echo So let me get this straight... echo Your favorite fruit is $fruit echo Your mama's name is $mama echo And you have been a little bitch for $years years.
当我输入Apples、Martha、3后,输出结果如下:
So let me get this straight... Your favorite fruit is Apples. Your mama's name is $mama And you have been a little bitch for $years
只有第一个变量能正常输出,其余变量均显示变量名。我尝试过修改变量命名和变量引用方式,但问题依旧。请问我是否忽略了某些细节,或是对read命令的变量处理逻辑存在误解?
问题原因与解决方法
问题出在脚本里的sleep2s这一行——sleep命令和它的参数之间必须有空格,写成sleep2s会被系统识别成一个不存在的命令,脚本执行到这里就会报错终止,后面的read命令根本没机会运行,mama和years变量自然没有被赋值,输出时就会直接显示变量名而非输入内容。
修正后的脚本只需要把错误的sleep2s改成sleep 2s即可:
read -p "What is your favorite fruit?" fruit echo Oh, I see... sleep 2s read -p "And what is your mama's name?" mama echo Amazing... sleep 2s read -p "And how many years have you been a little bitch?" years echo Understood... sleep 2s echo So let me get this straight... echo Your favorite fruit is $fruit echo Your mama's name is $mama echo And you have been a little bitch for $years years.
内容的提问来源于stack exchange,提问作者mvd
相关产品推荐
相关产品推荐

