You are not logged in.

#1 2005-11-20 04:32:09

stonecrest
Member
From: Boulder
Registered: 2005-01-22
Posts: 1,190

Bash for Dummies

Alright, this is pathetic that I have to ask but I can't figure it out for the life of me. I want a simple bash script that will take an argument (file name) and check if it exists. I have the following

if test -e $1
        then
                echo "true"
        else
                echo "false"
fi

It works, but only if the argument has no spaces. For example, the following don't work:
fileexists.sh "file name.jpg"
fileexists.sh file name.jpg

As you can see, I've tried escaping the space, putting the entire file name in spaces, I've tried putting quotes around the $1 in the script, etc. Please someone put me out of this misery  :x


I am a gated community.

Offline

#2 2005-11-20 04:53:49

Dusty
Schwag Merchant
From: Medicine Hat, Alberta, Canada
Registered: 2004-01-18
Posts: 5,986
Website

Re: Bash for Dummies

put quotes around the $1 parameter.

this works for me:

  if [ -e "$1" ] ; then
      echo 'true'
  else
      echo 'false'
  fi

Offline

#3 2005-11-20 04:57:36

xterminus
Member
From: Tacoma, WA, USA, Earth, Sol, M
Registered: 2005-10-30
Posts: 93

Re: Bash for Dummies

if [ -f "$@" ]; then
        echo true
else
        echo false
fi

The $@ allows testing against all arguments, which is needed even when your spaces are escaped.

There are a bunch of conditional tests in bash.  For a complete list, type man bash, then search for the phrase "CONDITIONAL EXPRESSIONS".

Offline

#4 2005-11-20 05:59:18

stonecrest
Member
From: Boulder
Registered: 2005-01-22
Posts: 1,190

Re: Bash for Dummies

Dusty, that is too weird that your way works but the way I put quotes around the $1 (below) didn't.

if test -e "$1"

Ah well, just glad to be able to use it. Thanks guys!


I am a gated community.

Offline

Board footer

Powered by FluxBB