0

I am trying to write a script which will tell if the file or directory exist or not. It will take the input " file name " from the user. First this will put the ls -l or ls output to a file and then take input from user (for filename), later will use if condition to check if file exist or not. But my code is not working.

# !/bin/bash
ls  > listtst.txt 
read -p "type file name" a
if [ listtst.txt  ==  $a  ];
  then
     echo "file is present $a"
  else
    echo "file not present"
fi
kvantour
  • 25,269
  • 4
  • 47
  • 72
Harshita
  • 1
  • 1
  • 2
  • What's the purpose of the file listtxt.txt in your example? BTW, your sheebang-line has a bang, but no shee, and the assignment to `b` is nonsense. – user1934428 Jan 03 '20 at 13:51
  • Thanks for pointing it out, I missed it while writing the code here. corrected it now – Harshita Jan 03 '20 at 14:04
  • You did, but you messed up the formatting of the remaining code ;-) – user1934428 Jan 03 '20 at 14:07
  • Yea. I am using stackoverflow for the first time. still learning ..will try to edit it again :p – Harshita Jan 03 '20 at 14:10
  • Your `if` condition checks uses `==`, which is not allowed in [ ... ] (see `man test` for the correct syntax). You could use `[[ == ]]`, if you need matching against a glob pattern, or `[ ... ]` for equality testing. The latter would just test, whether the user had entered the string _listtst.txt_, which is pointless: It is **obvious** that listtst.txt exists, because you have created this file just before.... – user1934428 Jan 03 '20 at 14:14
  • Thank you :) .. I checked man test – Harshita Jan 03 '20 at 14:31

1 Answers1

2

To check if file exist or not you can use:

FILE=/var/scripts/file.txt
if [ -f "$FILE" ]; then
    echo "$FILE exist"
else 
    echo "$FILE does not exist"
fi

Replace "/var/scripts/file.txt" with your file path

in case you need the file path to be a variable

you can replace the file path with $1

so your code will be:

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

and you have to call your script in this way:

./scriptname.sh "filepath"
Anthony Shahine
  • 2,477
  • 3
  • 18
  • 24