Tip: file_exists function

Often a wildcard test on files is needed.
Because test -f ... or [ -f ... ] have problems with zero or many arguments, and even [[ -f ... ]] has problems, and I have seen some ugly work-arounds,
I suggest the following simple function, to be defined somewhere at the beginning of the script:

file_exists() {
  for _i do [ -f "$_i" ] && return
  done
  return 1
}

It returns status 0 (success) if at least one of the given files was found,
and status 1 otherwise (the return 1 is necessary in case the nullglob option is on).
Examples:

if file_exists /tmp/*
then
  echo "at least one file is in /tmp"
fi
if file_exists /usr/lib/libtcl.so* /usr/lib/libtcl[0-9]*.so*
then
  echo "a libtcl is in /usr/lib"
fi

Analogue to file_exists() one can have the functions

dir_exists() {
  for _i do [ -d "$_i" ] && return
  done
  return 1
}

and

file_executable () {
  for _i do [ -f "$_i" -a -x "$_i" ] && return
  done
  return 1
}
3 Likes

Interesting.

But, as you test for any file, not a specific one, why not

file_exists() {   [ -f "$1" ] && return;   return 1; }

or even

file_exists() {   [ -f "$1" ];  return $?; }
1 Like

That would only test the first argument.
If the first matching /tmp/* token is a directory, it would return 1="no file found" regardless if a subsequent token is a file.

Ah - got you. Thanks!

EDIT: Nevermind, thats the purpose of your script :slight_smile: