2

My environment is:

  • CentOS 6.9
  • Ubuntu 16.04 LTS

The GNU coreutils 8.4 has the test command to check the file using -f option.

man test shows

  -f FILE
         FILE exists and is a regular file

The definition of the "regular file" is ambiguous for me.

On the terminal, I did

$ touch afile
$ ln -fs afile LN-FILE

Then, I executed the following script (check_file_exist_180320_exec)

#!/usr/bin/env bash
if [ -e LN-file ]
then
    echo "file exists [-e]"
fi

if [ -f LN-file ]
then
    echo "file exists [-f]"
fi

For CentOS and Ubuntu, both show -e and -f for symbolic linked file (LN-FILE).

However, ls -l returns l:symbolik link (not -:regular file) identifiers for the LN-FILE file. ( see. https://linuxconfig.org/identifying-file-types-in-linux)

On the other hand, I found following, Difference between if -e and if -f

A regular file is something that isn't a directory / symlink / socket / device, etc.

answered Apr 18 '12 at 7:10

jman

What is the reference I should check for the "regular file" (for CentOS and Ubuntu)?

sevenOfNine
  • 1,509
  • 16
  • 37

2 Answers2

5

Note the documentation further down in man test

Except for -h and -L, all FILE-related tests dereference symbolic links.

Basically when you do -f LN-file , and LN-file is a symbolic link, the -f test will follow that symlink, and give you the result of what the symlink points to.

If you want to check if a file is a symlink or a regular file, you need to do e.g.

if [ -h LN-file ]
then
    echo "file is a symlink [-h]"
elif [ -f LN-file ]
then
    echo "file is a regular file [-f]"
fi
nos
  • 223,662
  • 58
  • 417
  • 506
  • 1
    I see. The "-f" option checks the linked file, not the symbolic link and we should use it with care as your script (after -h check). – sevenOfNine Mar 20 '18 at 09:21
  • 1
    Almost every file interaction will cause a symlink to be dereferenced. And commonly one performs a `[ -f ]` test because some other program will interact with that file - that other program will see what the symlink points to, not that it's a symlink. So in most cases `[ -f ]` does what you want, and it's the special cases you need to care if the file is a symlink. – nos Mar 20 '18 at 09:33
  • To tell the truth, I do not come up with the case I should distinguish the regular file (non-symbolic link) and the symbolic link. So, as you told, in most cases `[ -f ]` may do what I want. – sevenOfNine Mar 20 '18 at 09:43
1

A regular file is a file that isn't a binary file neither a symbolic link. It use to be associated to a plain text file.

AlmuHS
  • 387
  • 6
  • 13