我想检查文件是否存在,如果不存在,我想询问用户是否要创建它。无论用户输入Y还是N,屏幕上都只会出现“Whatever you say”。
#!/bin/bash
#This is testing if a file (myFile) exists
if [ -f ~/myFile ]
then
echo "The file exists!"
else
echo "The file does not exist. Would you like to create it? (Y/N)"
read ANSWER
fi
if [ "$ANSWER"="N" ]
then
echo "Whatever you say!"
else
touch myFile
echo "The file has been created!"
fi
答案1
=
使用比较运算符时应使用空格。[ ]
是一个 shell 内置函数。因此,你必须用空格传递每个参数。所以你应该这样做:
if [ "$ANSWER" = "N" ]
答案2
您需要在=
运算符周围留有空格。
if [ "$ANSWER" = "N" ]
当我需要文本匹配时,我更喜欢使用case
overtest
或[ ... ]
,因为它更加灵活和高效。
FILE=~/myFile
if [ -f "$FILE" ]
then
echo "The file exists!"
else
echo -n "The file does not exist. Would you like to create it? (Y/N) "
read ANSWER
shopt -s nocasematch
case "$ANSWER" in
n|no)
echo "Whatever you say!"
;;
*)
touch "$FILE"
echo "The file has been created!"
;;
esac
shopt -u nocasematch
fi