1

How do you check if any file (the user chooses) exists in a certain place?

$org is a variable that I chose to set a path

if [ -e $org/$1]
then
echo "Do you want to overwrite"
exit 1

Do I use the if statement or getopts?

1
  • 1
    Your syntax is incorrect. There should be a space between $org/$1 and ]. The correct form is if [ -e $org/$1 ]. Take a look at my answer. Commented Jul 13, 2013 at 12:30

2 Answers 2

2

-f checks if the path exists and is a file

-d checks if the path exists and is a directory

2
  • this is part of my bash script for creating a recycle bin, is this syntax correct? if [ -e $org/$1] $org is the where the file originally existed. and I am doing this so if the the user is trying to a restore file and there is a file in the original destination with the same name, i want to ask the user 'do you want to overwrite?'
    – Tom
    Commented Jul 13, 2013 at 12:09
  • It may be worth noting that -f only detects regular files. It won't detect special files like device files or named pipes. It also won't match dead symlinks. Commented Jul 13, 2013 at 12:12
2

There should be a space between $org/$1 and ].

Try this:

if [ -e "$org/$1" ]; then
    echo "Do you want to overwrite"
fi

More information here: http://tldp.org/LDP/abs/html/fto.html

1
  • I think I misunderstood your question when writing this answer. I'm not familiar with getopts, but in simple situations, the if statement with -e "$org/$1" works fine. Commented Jul 13, 2013 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.