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
6
  • 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. Commented Jan 3, 2020 at 13:51
  • Thanks for pointing it out, I missed it while writing the code here. corrected it now Commented Jan 3, 2020 at 14:04
  • You did, but you messed up the formatting of the remaining code ;-) Commented Jan 3, 2020 at 14:07
  • Yea. I am using stackoverflow for the first time. still learning ..will try to edit it again :p Commented Jan 3, 2020 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.... Commented Jan 3, 2020 at 14:14

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

7 Comments

You might also use [[ -f $FILE ]] instead.
Both will check whether $FILE exists and is a plain file. For the OPs requirements, -e is a more appropriate test.
Thank you for your answer, but in this code we are explicitly mentioning the file name in first line (/var/scripts/file.txt) , I want user to give the file name as input.
check the update please @Harshita
@Harshita : Then just use the variable which you have in your code! In your code, the file is stored in a variable called a, so of course you just test with if [[ -e $a ]], whether such a directory entry exists!!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.