我设置:read -p "What will you like to name the file name? " filename
.但是,如果用户输入超过一个单词,脚本就会崩溃。如何检测用户输入是否有多个单词?
对不起!这是代码:
# provide option to rename the .ph file
while true do # 用户提示重命名文件并读取命令行参数 read -p "Would you like to change the file name? (Y/N) " 答案
# Handle user input
case $answer in
[Yy]* )
echo "Please enter a single word for file name. Otherwise the file name will be sequence.ph."
read -p "What will you like to name the file name? " filename
newname="$filename"
mv sequence.ph $filename.ph
echo "File has been renamed."
break
;;
[Nn]* )
newname="$1_tree"
mv sequence.ph $newname.ph
echo "Output file will have default name $1_tree.ph"
break
;;
* )
echo "Error: Invalid input."
echo "Please enter y/Y or n/N. "
;;
esac
done
答案1
如果您向read
命令提供多个要读取的变量,它会尝试将输入拆分为单词并为每个变量存储一个单词。因此,您可以给它两个变量,如果第二个变量中有任何内容,则输入了多个单词。像这样的东西:
while true; do
read -r -p "What will you like to name the file name? " filename extra # $extra will contain any extra word(s)
if [ -n "$extra" ]; then
echo "One-word filenames only, please"
else
break # Got a valid filename, so break out of the loop
fi
done
注意:我还添加了一个-r
选项,以read
防止它用反斜杠做奇怪的事情。可能不需要,但通常是一个好习惯。
...但多字文件名应该不是真正的问题。对于某些高级操作来说,正确处理它们可能有点棘手(请参阅Bash 常见问题解答 #20),但对于基本用途,您只需在变量引用两边加上双引号即可。像这样:
cat "$filename" # Works with multi-word filenames
cat $filename # FAILS with multi-word filenames - don't do this
双引号变量引用是总的来说是个好主意,所以即使您不允许(/期望)它们包含多个单词,您也应该这样做。shellcheck.net擅长指出变量应该用双引号引起来的地方,以及一堆其他常见的脚本错误(包括省略 选项-r
)read
,因此我建议通过它运行脚本。