![if 문을 올바르게 실행할 수 없습니다.](https://linux55.com/image/66034/if%20%EB%AC%B8%EC%9D%84%20%EC%98%AC%EB%B0%94%EB%A5%B4%EA%B2%8C%20%EC%8B%A4%ED%96%89%ED%95%A0%20%EC%88%98%20%EC%97%86%EC%8A%B5%EB%8B%88%EB%8B%A4..png)
파일이 존재하는지 확인하고, 존재하지 않으면 사용자에게 파일을 생성할지 묻고 싶습니다. 사용자가 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