How do I check if file exists in bash?
When I try to do it like this:
FILE1="${@:$OPTIND:1}"
if [ ! -e "$FILE1" ]
then
echo "requested file doesn't exist" >&2
exit 1
elif
<more code follows>
I always get following output:
requested file doesn't exist
The program is used like this:
script.sh [-g] [-p] [-r FUNCTION_ID|-d FUNCTION_ID] FILE
Any ideas please? I will be glad for any help.
P.S. I wish I could show the entire file without the risk of being fired from school for having a duplicate. If there is a private method of communication I will happily oblige.
My mistake. Fas forcing a binary file into a wrong place. Thanks for everyone's help.
Instead of plucking an item out of "$@" in a tricky way, why don't you
shift
off the args you've processed with getopts:Try to print FILE1 to see if it has the value you want, if it is not the problem, here is a simple script (site below):
http://www.cyberciti.biz/faq/unix-linux-test-existence-of-file-in-bash/
To (recap) and add to @DavidW.'s excellent answer:
Check the shebang line (first line) of your script to ensure that it's executed by
bash
: is it#!/bin/bash
or#!/usr/bin/env bash
?Inspect your script file for hidden control characters (such as
\r
) that can result in unexpected behavior; runcat -v scriptFile | fgrep ^
- it should produce NO output; if the file does contain\r
chars., they would show as^M
.\r
instances (more accurately, to convert Windows-style\r\n
newline sequences to Unix\n
-only sequences), you can usedos2unix file
to convert in place; if you don't have this utility, you can usesed 's/'$'\r''$//' file > outfile
(CAVEAT: use a DIFFERENT output file, otherwise you'll destroy your input file); to remove all\r
instances (even if not followed by\n
), usetr -d '\r' < file > outfile
(CAVEAT: use a DIFFERENT output file, otherwise you'll destroy your input file).(The purpose of enclosing the value in
[...]
(for example), is to see the exact boundaries of the values.)This will yield something like:
Note, though, that nothing at all is printed if no arguments were passed.
Little trick to debugging problems like this. Add these lines to the top of your script:
The
set -xv
will print out each line before it is executed, and then the line once the shell interpolates variables, etc. The$PS4
is the prompt used byset -xv
. This will print the line number of the shell script as it executes. You'll be able to follow what is going on and where you may have problems.Here's an example of a test script:
And here's what I get when I run it:
Here, I can see that I set
$FILE1
to.profile
, and that my script understood that${@:$OPTIND:1}
. The best thing about this is that it works on all shells down to the original Bourne shell. That means if you aren't running Bash as you think you might be, you'll see where your script is failing, and maybe fix the issue.I suspect you might not be running your script in Bash. Did you put
#! /bin/bash
on the top?You may want to use
getopts
to parse your parameters: