Find the answer to your Linux question:
Results 1 to 7 of 7
How do i check to see if a files exists in bash? I want to be able to see if the file exists and if it doesn't then create it. ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Sep 2005
    Posts
    99

    checking if a file exists


    How do i check to see if a files exists in bash? I want to be able to see if the file exists and if it doesn't then create it. I've tried:
    Code:
    if [ "<file path>" = "" ]
    then
      create the file
    fi
    however, this seems to just create a basic file with the name specified in "<file path>" and doesn't actually go into the if statement.

  2. #2
    Linux Enthusiast
    Join Date
    Aug 2006
    Posts
    631
    Code:
    man test
    Check the -e option.


    Regards

  3. #3
    Linux Guru Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,252
    There's a whole list of file tests at:
    http://www.tldp.org/LDP/abs/html/fto.html

  4. $spacer_open
    $spacer_close
  5. #4
    Just Joined!
    Join Date
    Sep 2005
    Posts
    99
    ok so if test -e returns true if the file exists to check that it doesn't exist what would i do? I treid just entering the command test -e and then a file name and for both a file that exists and a file that doesn't exist no feed back is printed on the screen Could i do it like a ! thing like have the if statement say:
    Code:
    if [ !test -e <file_name> ]
    then
      create the file
    fi

  6. #5
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    Quote Originally Posted by cwl157
    ok so if test -e returns true if the file exists to check that it doesn't exist what would i do? I treid just entering the command test -e and then a file name and for both a file that exists and a file that doesn't exist no feed back is printed on the screen Could i do it like a ! thing like have the if statement say:
    Code:
    if [ !test -e <file_name> ]
    then
      create the file
    fi
    without using "test"
    Code:
    if [ ! -f "file" ]
    then
       #do something
    fi
    note, when using -e, a directory called "file" will also be considered found.

  7. #6
    Just Joined!
    Join Date
    Sep 2005
    Posts
    99
    thanks, now how about a check like that to see if a directory exists?

  8. #7
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    Quote Originally Posted by cwl157
    thanks, now how about a check like that to see if a directory exists?
    please read this link given to you. The -d option checks for directory.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •