
파일이 존재하는지 확인하고, 존재하지 않으면 사용자에게 파일을 생성할지 묻고 싶습니다. 사용자가 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
=
비교 연산자를 사용할 때는 공백을 사용하세요. [ ]
쉘 내장 함수입니다. 따라서 각 매개변수를 공백과 함께 전달해야 합니다. 그래서 당신은 이렇게 해야 합니다:
if [ "$ANSWER" = "N" ]
답변2
=
연산자 주위에 공백이 필요합니다 .
if [ "$ANSWER" = "N" ]
텍스트 일치가 필요할 때 case
over test
or 를 사용하는 것이 [ ... ]
더 유연하고 효율적이기 때문에 선호합니다.
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