I am trying to write a shell script but I only want it to run if there are no files with a specific name found on the server. I know how to check for a specif file which would be done like this:

if [ -f /path/to/file ]
then
    echo The file already exists
else
    touch /path/to/file
fi

The above requires that I know the path to the file however. The script I am creating is supposed to search the server to see if a file with that name already exists and if it doesn't, run the commands and preferably, if the file does exist, display it's location but I can't figure out how this would be done.

I can use find to specify the file like so:

find / -name "filename"

Which either comes up with results or nothing, which is expected. What I want to happen is if find has no results then I want it to run a command and if it does have results, display those results. Here's some pseudo code of what I want it to do:

if [ find / -name "filename" > 0 ]
then
    echo The file already exists at (location)
else
    create the file
fi

Hopefully that makes sense.

hi,

what shell are you using?

ksh can pipe find's output to a while read loop to create an array (if [ ${#array[@]} -gt 0 ];... )
bash has process substitution to do the same.
sh, using command substitution, will just let you know a variable has been set, this variable will contain all the files found. :(

It's just a basic bash script.

The solution was a lot simpler than I was making it. Since I only actually needed the first output from the find, I just put it in to a variable which meant only the first result was written and then checked if the variable had content:

#!/bin/bash
location=(`find / -maxdepth 4 -name "filename"`)

if [ $location ]
then
     echo The file already exists at $location
else
     touch /path/to/file
     echo The file has been created.
fi

For those who are curiou, the reason I have the -maxdepth parameter is because there's only a few locations the file would be. The script isn't actually checking for a file but rather a program. If it's not installed, it installs it then runs it but if it's already installed, it'll simply run it.

GNUfind has -quit, so it stops searching as soon as it finds a matching file

#!/bin/bash

location=$(find / -maxdepth 4 -type f -name "filename" -print -quit)
if test -n "$location"
then
   echo "The file already exists at $location"
else
   touch /path/to/file
   echo "The file has been created."
fi
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.