3

Using if [ -f "file" ] works on non-hidden files.
I'm trying to use it for a hidden file: if [ -f ".file" ] and of course it returns false (even that .file exists).

If I use if [ -f -a "file" ] it returns true for all hidden files (that is, if 'any' file is hidden).

How can I check if a .someFile exists (where 'someFile' is a hidden file)?

3
  • 1
    I suggest: help test
    – Cyrus
    Apr 21, 2018 at 12:25
  • @Cyrus Ok, now I feel dumb. It's all there, listed green on black. Thanks!
    – bauerMusic
    Apr 21, 2018 at 13:31
  • 2
    if [ -f "file" ] will work fine for detecting hidden (but otherwise normal) files. If it's failing, you probably have something like a symbolic link to a file elsewhere; that's not a regular file, so the -f test will return false. It has nothing to do with whether it's hidden or not. Apr 21, 2018 at 17:22

3 Answers 3

2

Ok, found it (by just trying really). Need to use -a instead of -f:
if [ -a ".file" ]

-Edit-

Following the great advice by Cyrus, $ help test will list all the test options. Specifically:
-a FILE True if file exists.
-f FILE True if file exists and is a regular file.

2
  • 1
    what if it's a directory
    – baxx
    Jul 29, 2020 at 21:43
  • 1
    [ -a or test -a works in Bash. It may not work in sh. POSIX specifies [ -e for this. [ -e works in Bash as well. The question is tagged bash, so [ -a is a good answer. Still [ -e would be better because of its portability. Sep 21, 2021 at 14:34
2

using -e works for me:

if [ -e ${file} ]; then
   echo "${file} exists even if it's hidden"
fi
-1

For people looking for hidden directory check solution, this works for me:

HIDDEN_DIR=$(ls -a /dir_path | grep '.dir_name')
if [[ $HIDDEN_DIR == ".dir_name" ]]; then
  echo "hidden dir exists"
fi
1
  • 1
    -1. So flawed. (1) Parsing ls is wrong. (2) A dot in regex matches any character, so adir_name will match. (3) foo.dir_name1 will also match. (4) What if there are two matching entries? (5) Any match can be a non-directory, but your code states hidden dir exists without checking the type. Sep 21, 2021 at 3:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .