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?

5
  • 2
    if [[ -e "$1" ]]; then echo "file exists"; else echo "file not exists"; fi? Commented Mar 31, 2018 at 18:14
  • 1
    Cult-cargo programming spotted Commented Mar 31, 2018 at 18:15
  • Thanks to read doc : FAQ: mywiki.wooledge.org/BashFAQ | Guide: mywiki.wooledge.org/BashGuide | Ref: gnu.org/s/bash/manual | wiki.bash-hackers.org | mywiki.wooledge.org/Quotes | Check your script: 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. Commented Mar 31, 2018 at 18:21
  • @GillesQuenot, I hadn't heard that term. That's awesome, I will use it. :-D Commented Mar 31, 2018 at 18:22
  • You're welcome @ghoti, with pleasure Commented Mar 31, 2018 at 18:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

So if statement has its own "commands"?
@Iomanip, it is like checks you could say, see man test for more details.
help [[ and no need quoting inside [[ ]]
@Down voter, what is the reason of down vote? I never get a reply to it from down voters :(
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.