Rectangle 27 28

-L is the test for file exists and is also a symbolic link

If you do not want to test for the file being a symbolic link, but just test to see if it exists regardless of type (file, directory, socket etc) then use -e

So if file is really file and not just a symbolic link you can do all these tests and get an exit status whose value indicates the error condition.

if [ ! \( -e "${file}" \) ]
then
     echo "%ERROR: file ${file} does not exist!" >&2
     exit 1
elif [ ! \( -f "${file}" \) ]
then
     echo "%ERROR: ${file} is not a file!" >&2
     exit 2
elif [ ! \( -r "${file}" \) ]
then
     echo "%ERROR: file ${file} is not readable!" >&2
     exit 3
elif [ ! \( -s "${file}" \) ]
then
     echo "%ERROR: file ${file} is empty!" >&2
     exit 4
fi

-e "${file}" fails if the symlink exists but its target does not exist.

Same result as Flimm. I'm on OS X. For me, -L and -h work for symlinks, but not -e or -f.

@Flimm, so if I just want to test if a filename is taken (whether it's a file or symlink without target existing) what's the best way to do it? apparently -e doesn't work

bash - How to check if a symlink exists - Stack Overflow

bash symlink
Rectangle 27 3

With BASH it is easy to test if file exists before reading it in

[ -e file ] && var=$(< file )

As Inian points in the comments the file might exist but the user might not have sufficient rights for reading it. The -r test would take care of that.

[ -r file ] && var=$(< file )

Does this handle the error stream when the file exists and permission is denied for the file?

True, but isn't this even worse than my alternatives: 1. Additional check and code branch (and potential race condition if the file vanishes between the two) 2. Issues with -e vs. -r (as @Inian also commented on) 3. Need to initialize var= in addition 4. Probably (slightly) worse performance

Poor performance is baked into the shell :) Don't worry about unavoidable and negligible things like this.

bash - Read file into variable while suppressing "No such file or dire...

bash
Rectangle 27 8

I use below function to test if file exists. It catches also other exceptions. So in case there are rights issues e.g. chmod ugo-rwx filename or in Windows Right Click -> Properties -> Security -> Advanced -> Permission entries: empty list .. function returns exception as it should. The file exists but we don't have rights to access it. It would be wrong to ignore this kinds of exceptions.

function fileExists(path) {

  try  {
    return fs.statSync(path).isFile();
  }
  catch (e) {

    if (e.code == 'ENOENT') { // no such file or directory. File really does not exist
      console.log("File does not exist.");
      return false;
    }

    console.log("Exception fs.statSync (" + path + "): " + e);
    throw e; // something else went wrong, we don't have rights, ...
  }
}
{
  [Error: ENOENT: no such file or directory, stat 'X:\\delsdfsdf.txt']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'stat',
  path: 'X:\\delsdfsdf.txt'
}

Exception in case we don't have rights to the file, but exists:

{
  [Error: EPERM: operation not permitted, stat 'X:\file.txt']
  errno: -4048,
  code: 'EPERM',
  syscall: 'stat',
  path: 'X:\\file.txt'
}

Really like this, it's one of the few answers that's up to date since node has deprecated the last 37 ways of doing this

Check synchronously if file/directory exists in Node.js - Stack Overfl...

node.js
Rectangle 27 8

I use below function to test if file exists. It catches also other exceptions. So in case there are rights issues e.g. chmod ugo-rwx filename or in Windows Right Click -> Properties -> Security -> Advanced -> Permission entries: empty list .. function returns exception as it should. The file exists but we don't have rights to access it. It would be wrong to ignore this kinds of exceptions.

function fileExists(path) {

  try  {
    return fs.statSync(path).isFile();
  }
  catch (e) {

    if (e.code == 'ENOENT') { // no such file or directory. File really does not exist
      console.log("File does not exist.");
      return false;
    }

    console.log("Exception fs.statSync (" + path + "): " + e);
    throw e; // something else went wrong, we don't have rights, ...
  }
}
{
  [Error: ENOENT: no such file or directory, stat 'X:\\delsdfsdf.txt']
  errno: -4058,
  code: 'ENOENT',
  syscall: 'stat',
  path: 'X:\\delsdfsdf.txt'
}

Exception in case we don't have rights to the file, but exists:

{
  [Error: EPERM: operation not permitted, stat 'X:\file.txt']
  errno: -4048,
  code: 'EPERM',
  syscall: 'stat',
  path: 'X:\\file.txt'
}

Really like this, it's one of the few answers that's up to date since node has deprecated the last 37 ways of doing this

Check synchronously if file/directory exists in Node.js - Stack Overfl...

node.js
Rectangle 27 9

Don't. Just catch the FileNotFoundException. The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:

  • the timing window problem whereby the file might exist when you test but not when you open, or vice versa, and
  • the fact that, as the existence of this question shows, you might make the wrong test and get the wrong answer.

Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.

What if I want to check every hour to see if a file has been deposited on a directly location. I have a webMethods project that has to check to see if a specific file has been uploaded to a specific drive. How would this be done. Let's say that I want to check every hour to see if the file is there. I can use Java to write a class that does this probably with a timer of some sort.

Catching an exception is way more expensive. In my test, checking new File().exists() was more than 10 times faster than catching FileNotFoundException. So, if you have a scenario where files normally expected to be missing (such as disk cache), exception is wrong. Also, second-guessing the system is cool.

@Gnawer You haven't addressed any of the issues I raised; the exception is only thrown when the file can't be opened; and operations that occur once an hour don't require micro-optimization. Your final sentence is nonsense.

@DougHauf in your case there's no issue since you don't attempt to do anything after you check existence. But the OP asked specifically to check before opening. In this case it's better to just try/catch the file open.

How do I check if a file exists in Java? - Stack Overflow

java file-io io
Rectangle 27 9

Don't. Just catch the FileNotFoundException. The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:

  • the timing window problem whereby the file might exist when you test but not when you open, or vice versa, and
  • the fact that, as the existence of this question shows, you might make the wrong test and get the wrong answer.

Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.

What if I want to check every hour to see if a file has been deposited on a directly location. I have a webMethods project that has to check to see if a specific file has been uploaded to a specific drive. How would this be done. Let's say that I want to check every hour to see if the file is there. I can use Java to write a class that does this probably with a timer of some sort.

Catching an exception is way more expensive. In my test, checking new File().exists() was more than 10 times faster than catching FileNotFoundException. So, if you have a scenario where files normally expected to be missing (such as disk cache), exception is wrong. Also, second-guessing the system is cool.

@Gnawer You haven't addressed any of the issues I raised; the exception is only thrown when the file can't be opened; and operations that occur once an hour don't require micro-optimization. Your final sentence is nonsense.

@DougHauf in your case there's no issue since you don't attempt to do anything after you check existence. But the OP asked specifically to check before opening. In this case it's better to just try/catch the file open.

How do I check if a file exists in Java? - Stack Overflow

java file-io io
Rectangle 27 9

Don't. Just catch the FileNotFoundException. The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:

  • the timing window problem whereby the file might exist when you test but not when you open, or vice versa, and
  • the fact that, as the existence of this question shows, you might make the wrong test and get the wrong answer.

Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.

What if I want to check every hour to see if a file has been deposited on a directly location. I have a webMethods project that has to check to see if a specific file has been uploaded to a specific drive. How would this be done. Let's say that I want to check every hour to see if the file is there. I can use Java to write a class that does this probably with a timer of some sort.

Catching an exception is way more expensive. In my test, checking new File().exists() was more than 10 times faster than catching FileNotFoundException. So, if you have a scenario where files normally expected to be missing (such as disk cache), exception is wrong. Also, second-guessing the system is cool.

@Gnawer You haven't addressed any of the issues I raised; the exception is only thrown when the file can't be opened; and operations that occur once an hour don't require micro-optimization. Your final sentence is nonsense.

@DougHauf in your case there's no issue since you don't attempt to do anything after you check existence. But the OP asked specifically to check before opening. In this case it's better to just try/catch the file open.

How do I check if a file exists in Java? - Stack Overflow

java file-io io
Rectangle 27 1

I created a file named test with no extension in the folder M:\Incoming.

Running the following code works in both cases:

if (File.Exists(@"M:\Incoming\test"))
    Console.WriteLine("Exists");

if (File.Exists(@"M:\\Incoming\\test"))
    Console.WriteLine("Exists");

When using @ you do not need to specify two slashes, although it makes no difference anyway in this example.

Your problem is most likely to be in the way in which you are concatenating the strings.

How to check if a file exists when it was no file extension? C# - Stac...

c# file io exists
Rectangle 27 6

In your unit test it seems that you are deploying an xml file: TestData\BuildMachineNoNames.xml which you are passing to the GetBuildMachineNames. So the file exists and you cannot expect a FileNotFoundException to be thrown. So maybe like this:

[TestMethod]
[ExpectedException(typeof(FileNotFoundException), "Raise exception when file not found")]
public void VerifyBuildMachineNamesIfFileNotPresent()
{
    var configReaderNoFile = new ConfigReader();
    var names = configReaderNoFile.GetBuildMachineNames("unexistent.xml");
}

No!! Even I am passing, but its giving wrong path, so other tests are also getting fail, becasue path not correct then this perticular test should pass, what i wrote for file nt found exception.

@Pawan, is FileNotFoundException actually thrown inside the GetBuildMachineNames method? If yes, then this test should pass. If no exception or another type of exception is thrown the test will fail.

Sorry, i am new in this area. Actually I was not running the unit test, i was debugging that.... Above code is correct. Jst one modification I made is in file property I set to "always copy"

c# - Exception in MS Unit Test? - Stack Overflow

c# unit-testing expected-exception
Rectangle 27 3

You can use the test(7) command to check if a file exists so all you have to do is loop over the expected files and add them to an array if they don't exist.

# The target files
FILES=(
    "prefix_alpha.txt"
    "prefix_beta.txt"
    "prefix_gamma_.txt"
    "prefix_delta.txt"
    "prefix_epsilon.txt"
    "prefix_feta.txt"
)

# Create a missing array
declare -a MISSING

for file in "${FILES[@]}"; do
    test -e "$file" || MISSING+=("$file")
done

echo "${MISSING[@]}"

bash - How do I grab files that don't exist and store them into a vari...

bash
Rectangle 27 3

You can use the test(7) command to check if a file exists so all you have to do is loop over the expected files and add them to an array if they don't exist.

# The target files
FILES=(
    "prefix_alpha.txt"
    "prefix_beta.txt"
    "prefix_gamma_.txt"
    "prefix_delta.txt"
    "prefix_epsilon.txt"
    "prefix_feta.txt"
)

# Create a missing array
declare -a MISSING

for file in "${FILES[@]}"; do
    test -e "$file" || MISSING+=("$file")
done

echo "${MISSING[@]}"

bash - How do I grab files that don't exist and store them into a vari...

bash
Rectangle 27 14

These answers are no longer recommended since try_files works faster than if in this context. Simply add try_files in your php location block to test if the file exists, otherwise return a 404.

location ~ \.php {
    try_files $uri =404;
    ...
}

php - Nginx - Customizing 404 page - Stack Overflow

php nginx http-status-code-404
Rectangle 27 255

Maybe you have a file/directory named test in the directory. If this directory exists, and has no dependencies that are more recent, then this target is not rebuild.

To force rebuild on these kind of not-file-related targets, you should make them phony as follows:

.PHONY: all test clean

Note that you can declare all of your phony targets there.

I had a directory called build and another called lib. In hindsight, these are not perfect target names. Ugh.....make.

*Where all, test, and clear are your makefile target names

Another solution is changing the label. In your case, change test for test_rule or something different.

makefile - Why does make think the target is up to date? - Stack Overf...

makefile
Rectangle 27 1

If you want to test if a file exists, look at available

But then once you use available and set a property to true how do you use that as a dependency for a target?

Read ant.apache.org/manual/targets.html : "A target also has the ability to perform its execution if (or unless) a property has been set"

In an Ant build script, how do you check for the existence of a file o...

ant build dependencies
Rectangle 27 1

This happens because you have literal quotes in your string, and they are not being interpreted as shell script code.

$x="1+1";
echo 1+1;   # Writes 2
echo $x;    # Writes 1+1, not 2

It works the same way in Bash:

var="'myfile'"
[[ -e 'myfile' ]]  # Checks for a file called  myfile 
[[ -e $var ]]      # Checks for a filename with apostrophes in it, not  myfile

You have to extract the exact filename you want. Since your filename doesn't contain apostrophes, you should strip them:

var="'myfile'"
var=${var//\'/}  # Replace all apostrophes with nothing
if [[ -e $var ]]
then
  echo "Exists"
fi

In BASH, test if file exists does not work when filename in variable h...

bash ifs
Rectangle 27 3

You just need to pass the 'wx' flags to fs.writeFile(). This will create and write the file if it does not exist or will return an error if the file already exists. This is supposed to be free of race conditions which fs.exist() and fs.access() are subject to because they don't have the ability to test and create the file in an atomic action that cannot be interrupted by any other process.

Here's an encapsulated version of that concept:

// define version of fs.writeFile() that will only write the file
// if the file does not already exist and will do so without
// possibility of race conditions (e.g. atomically)
fs.writeFileIfNotExist = function(fname, contents, options, callback) {
    if (typeof options === "function") {
        // it appears that it was called without the options argument
        callback = options;
        options = {};
    }
    options = options || {};
    // force wx flag so file will be created only if it does not already exist
    options.flag = 'wx';
    fs.writeFile(fname, contents, options, function(err) {
        var existed = false;
        if (err && err.code === 'EEXIST') {
           // This just means the file already existed.  We
           // will not treat that as an error, so kill the error code
           err = null;
           existed = true;
        }
        if (typeof callback === "function") {
           callback(err, existed);
        }
    });
}

// sample usage
fs.writeFileIfNotExist("myFile.json", someJSON, function(err, existed) {
    if (err) {
        // error here
    } else {
        // data was written or file already existed
        // existed flag tells you which case it was
    }
});
fs.writeFile()

Node.js - Write json if file doesn't exist [not using fs.exists()] - S...

node.js
Rectangle 27 3

You just need to pass the 'wx' flags to fs.writeFile(). This will create and write the file if it does not exist or will return an error if the file already exists. This is supposed to be free of race conditions which fs.exist() and fs.access() are subject to because they don't have the ability to test and create the file in an atomic action that cannot be interrupted by any other process.

Here's an encapsulated version of that concept:

// define version of fs.writeFile() that will only write the file
// if the file does not already exist and will do so without
// possibility of race conditions (e.g. atomically)
fs.writeFileIfNotExist = function(fname, contents, options, callback) {
    if (typeof options === "function") {
        // it appears that it was called without the options argument
        callback = options;
        options = {};
    }
    options = options || {};
    // force wx flag so file will be created only if it does not already exist
    options.flag = 'wx';
    fs.writeFile(fname, contents, options, function(err) {
        var existed = false;
        if (err && err.code === 'EEXIST') {
           // This just means the file already existed.  We
           // will not treat that as an error, so kill the error code
           err = null;
           existed = true;
        }
        if (typeof callback === "function") {
           callback(err, existed);
        }
    });
}

// sample usage
fs.writeFileIfNotExist("myFile.json", someJSON, function(err, existed) {
    if (err) {
        // error here
    } else {
        // data was written or file already existed
        // existed flag tells you which case it was
    }
});
fs.writeFile()

Node.js - Write json if file doesn't exist [not using fs.exists()] - S...

node.js
Rectangle 27 1

-a as a test if a file exists, is a unary expression ( one-sided ) is a remnant of ksh86 (KornShell 86). It has become obsolete in more modern, derivative shells and has been replaced by -e which is part of the POSIX standard, but in many shells it is still a synonym of -e for backwards compatibility.

-a can also be used a binary expression (two sided) and then it means an AND logical operator (which is also obsolescent). Here -a is interpreted this way because there is a ! symbol in front of it and a string behind it. Both sides evaluate to true, so by using AND the outcome then becomes logically true.

Using -e fixes this since it cannot be interpreted in another way.

Another way would have been to negate that outcome of the test command like so:

if ! [ -a $HOME/.some_directory ] ; then
if [ ! \( -a $HOME/.some_directory \) ] ; then

But at any rate it is better to stick with operands that are not deprecated / obsolescent..

linux - Why does negated file existence check in bash return weird res...

linux bash shell if-statement
Rectangle 27 1

-a as a test if a file exists, is a unary expression ( one-sided ) is a remnant of ksh86 (KornShell 86). It has become obsolete in more modern, derivative shells and has been replaced by -e which is part of the POSIX standard, but in many shells it is still a synonym of -e for backwards compatibility.

-a can also be used a binary expression (two sided) and then it means an AND logical operator (which is also obsolescent). Here -a is interpreted this way because there is a ! symbol in front of it and a string behind it. Both sides evaluate to true, so by using AND the outcome then becomes logically true.

Using -e fixes this since it cannot be interpreted in another way.

Another way would have been to negate that outcome of the test command like so:

if ! [ -a $HOME/.some_directory ] ; then
if [ ! \( -a $HOME/.some_directory \) ] ; then

But at any rate it is better to stick with operands that are not deprecated / obsolescent..

linux - Why does negated file existence check in bash return weird res...

linux bash shell if-statement
Rectangle 27 2

test -f filename && daemon.py restart || echo "File doesn't exists"

linux - How can I check a file exists and execute a command if not? - ...

linux shell