0

I want to check if a file exists, and if it doesn't exists, I want to ask the user if they'd like to create it. Whether the user inputs Y or N, only "Whatever you say" appears on the screen.

#!/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
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
ara6
  • 1

2 Answers2

1

You should use whitespace when using the = comparison operator. [ ] is a shell builtin function. Hence, you have to pass every argument with spaces. So you should do it this way:

if [ "$ANSWER" = "N" ]

Source: http://www.tldp.org/LDP/abs/html/comparison-ops.html

shivams
  • 4,565
0

You need spaces around = operator.

if [ "$ANSWER" = "N" ]

When I need text matching I prefer using case over test or [ ... ], because it's more flexible and efficient.

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
yaegashi
  • 12,326