1

I am trying to make script which will check if file exists. Filename is passed by argument. The script is checking if file exists in current directory.

#!/bin/bash

tmp=$(find $1)
failure="find: ‘$1‘: No such file or directory"

if [ "$tmp" != "$failure" ]; then
        echo "file exists"
else
        echo "file not exists"
fi

I am creating two variables. First one holds result of find command, and the second one holds the failure message of find command. In if statement I am comparing those variables.

Even if file exists I am getting always else statement message. What is wrong with this code?

Iomanip
  • 71
  • 1
  • 4
  • 2
    `if [[ -e "$1" ]]; then echo "file exists"; else echo "file not exists"; fi`? – Cyrus Mar 31 '18 at 18:14
  • 1
    Cult-cargo programming spotted – Gilles Quénot Mar 31 '18 at 18:15
  • Thanks to read doc : FAQ: http://mywiki.wooledge.org/BashFAQ | Guide: http://mywiki.wooledge.org/BashGuide | Ref: http://gnu.org/s/bash/manual | http://wiki.bash-hackers.org/ | http://mywiki.wooledge.org/Quotes | Check your script: http://www.shellcheck.net/ And avoid people recommendations saying to learn with tldp.org web site, the tldp bash guide is outdated, and in some cases just plain wrong. – Gilles Quénot Mar 31 '18 at 18:21
  • @GillesQuenot, I hadn't heard that term. That's awesome, I will use it. :-D – ghoti Mar 31 '18 at 18:22
  • You're welcome @ghoti, with pleasure – Gilles Quénot Mar 31 '18 at 18:25

1 Answers1

3

No need to use find in case your file is in current path itself, following may help you.

#!/bin/bash
filename=$1
if [[ -f "$filename" ]]; then
        echo "file exists"
else
        echo "file does not exists"
fi

Then run script as script.ksh file_name Also in case you need to verify if file exists and is having some size then change -f to -s in above code.

You could also do man test for checking all these kind of conditions too in your box.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • So if statement has its own "commands"? – Iomanip Mar 31 '18 at 18:20
  • @Iomanip, it is like checks you could say, see `man test` for more details. – RavinderSingh13 Mar 31 '18 at 18:22
  • `help [[` and no need quoting inside `[[ ]]` – Gilles Quénot Mar 31 '18 at 20:11
  • @Down voter, what is the reason of down vote? I never get a reply to it from down voters :( – RavinderSingh13 Mar 31 '18 at 22:01
  • @GillesQuenot Quoting is *sometimes* unneeded inside `[[ ]]`, but sometimes it is needed. For example, in `[[ $a = $b ]]`, the value of `$a` will be treated as a literal string whether it's quoted or not, but the value of `$b` will be treated as a glob pattern unless it's quoted. IMO it's easier to just double-quote all variable expansions than to keep track of where it's safe to leave the quotes off. – Gordon Davisson Apr 01 '18 at 01:45