Calyo Delphi
Calyo Delphi

Reputation: 349

bash check if file exists anywhere

I have access to a CentOS web server with multiple user accounts on it. These users could have php.ini files anywhere in their own branches of the file system--not just in their home directories. I am trying to find a simple and elegant way (preferably using bash utilities) to test if a php.ini file exists anywhere within a single user's branch of the file system.

The examples below show the only two methods that I am able to devise, but each has their drawbacks that makes them unusable:

# Does not work as intended
# Always echoes "Found" because find returns 0 even if it didn't find php.ini
if find . -name php.ini; then echo "Found"; fi

# Does not work if php.ini is in a subdirectory
# This test only works on the current working directory
if [ -e php.ini ]; then echo "Found"; fi

Assuming that the current working directory is ~ (/home/user) and the php.ini file is in ~/public_html, the output of each is thus:

# First, if the php.ini is named php.ini:
[email protected] [~]# if find . -name php.ini; then echo "Found"; fi
./public_html/php.ini
Found
# After renaming php.ini to php.ini.bak to test find's exit status:
[email protected] [~]# if find . -name php.ini; then echo "Found"; fi
Found

# And using the -e file test operator, with php.ini correctly named:
[email protected] [~]# if [ -e php.ini ]; then echo "Found"; fi

Any ideas on how to make this work using primarily bash utilities?

Upvotes: 1

Views: 2903

Answers (2)

that other guy
that other guy

Reputation: 123410

Check whether find outputs anything:

if [[ $(find . -name php.ini) ]]
then
  echo "Found"
fi

With GNU find, you can also make it exit immediately when a match is found:

if [[ $(find . -name php.ini -print -quit) ]]
then
  echo "Found"
fi

Upvotes: 7

arielCo
arielCo

Reputation: 431

if [ -e "$(find . -name 'php.ini' | head -1)" ] ; then echo "Found"; fi

The double quotes are necessary because [ -e ] exits with code 0.

Upvotes: 1

Related Questions