1

I'm wondering how to control where my if statements find files.

The code if [ -e filename ] should find a file, but where is it looking?

I have the following code I'm having trouble with:

#!/bin/bash
#create a new file
echo "Enter the customer data"
read -p "Email:" cemail
read -p "Name:" cname
read -p "Apt:" capt
read -p "Monthly Rent:" crent
read -p "Rent Due Date:" cdatedue

echo "$cemail"
#if its already a file then error
if [ -e "$cemail" ]
then
    echo "Error: customer already exists"
    exit 1
else
    echo "ok"
fi

when I type in a filename that does exist it still isn't finding it. Our programs are in the :~/courses/cs3423/2017Fa/Proj1 folder and the files we are searching against are in the :~/courses/cs3423/2017Fa/Proj1/Data folder. And this is how the program has to be set up as well. How can I manipulate the if to function correctly, or do I need to use something else? Thanks.

Jayveer Parmar
  • 500
  • 7
  • 25
  • No tricks Anthony, bash simply does what you tell it to do. First, strange, but you are testing for `cemail`? That's fine if that holds a filename, but if `cemail` holds an e-mail address, then of course it won't find anything. Why not start with something simple (since `-e` will match either files or directories), like `mydir=$HOME; if [ -e "$mydir" ]; then echo "found $mydir"; else echo "$mydir not found"; fi` – David C. Rankin Sep 04 '17 at 03:22
  • yes, the email is also the name of the file. So it looks like I need to put if [ -e "/Data/$cemail" ] from what youre saying – Anthony Capps Sep 04 '17 at 04:19
  • @AnthonyCapps No, since that starts with `/`, it'll be treated as an absolute path, i.e. it starts at the top level of the system volume. If you use an absolute path, you must use the *complete* absolute path. If you want to find it relative to the directory the script's in, you must first find the script's directory; see [this question](https://stackoverflow.com/questions/59895/getting-the-source-directory-of-a-bash-script-from-within) for ways to do that. – Gordon Davisson Sep 04 '17 at 17:33
  • Both of these comments help my understanding. Thank you. I'm just starting with Linux and the filenames/paths is definitely something I need to lock down how to manipulate. – Anthony Capps Sep 04 '17 at 22:45

0 Answers0