Jump to content

Linux/Bash: Check if a file exists

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
Tor

Tor

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 486 posts
I use this little script in some of my larger bash scripts and thought I would share:

#!/bin/bash
# Check if a file exists
#
# Usage: ./file.sh <filename>
#

if [ -f $1 ]
then
    echo "$1 file exists"
else
    echo "$1 file does not exist"
fi

Usage: ./file.sh <filename>

Example:
# ./file.sh test

Output:
./file.sh test
test file exists

Attached Files

  • Attached File  file.sh   168bytes   227 downloads


#2
asafe

asafe

    Programmer

  • Members
  • PipPipPipPip
  • 107 posts
-e checks if a file exist too.

#3
relapse

relapse

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 476 posts
What does -e and -f even mean?

#4
asafe

asafe

    Programmer

  • Members
  • PipPipPipPip
  • 107 posts
Those options belong to test.
Run man test and you'll see a list of possible options and its meanings.
if [ -f $1 ]
In shell script the [ ] indicate a test so you can omit the word test.

#5
relapse

relapse

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 476 posts
Oh, I see. There are several options that test a file for bash scripting:

       FILE1 -ot FILE2
              FILE1 is older than FILE2

       -b FILE
              FILE exists and is block special

       -c FILE
              FILE exists and is character special

       -d FILE
              FILE exists and is a directory

       -e FILE
              FILE exists

       -f FILE
              FILE exists and is a regular file

       -g FILE
              FILE exists and is set-group-ID

       -G FILE
              FILE exists and is owned by the effective group ID

       -h FILE
              FILE exists and is a symbolic link (same as -L)

       -k FILE
              FILE exists and has its sticky bit set

       -L FILE
              FILE exists and is a symbolic link (same as -h)

       -O FILE
              FILE exists and is owned by the effective user ID

       -p FILE
              FILE exists and is a named pipe

       -r FILE
              FILE exists and read permission is granted
       -s FILE
              FILE exists and has a size greater than zero

       -S FILE
              FILE exists and is a socket

       -t FD  file descriptor FD is opened on a terminal

       -u FILE
              FILE exists and its set-user-ID bit is set

       -w FILE
              FILE exists and write permission is granted

       -x FILE
              FILE exists and execute (or search) permission is granted