Searching files

i want to search a file bt it not happening i m using

#!bin/bash
read file
 if (-e "$file")
then
echo "asfsafafa"
else
 echo "NO SUCH FILE"
fi

....error

./VMC.sh: line 5: [fegsgws]: command not found
NO SUCH FILE
;;;;;;;;;;

its giving correctly no such file found but whats is command not found.

The following need to be modified.

if (-e "$file") ==> if [ -e $file ]

Cheers,

1 Like

noo thats not working

it should work..
Please check..

$ cat file2
read file
if [[ -e "$file" ]]
then
echo "asfsafafa"
else
echo "NO SUCH FILE"
fi
$ sh file2
file
asfsafafa

$ sh file2
no_file
NO SUCH FILE

And your script also can be written as..

read file
[[ -e "$file" ]] && echo "Pass" || echo "Fail"
1 Like

I have tested it below

# ./test.sh
aaaa
./test.sh: line 2: -e: command not found
NO SUCH FILE
# vi test.sh
 # ./test.sh
asdfa
NO SUCH FILE
# cat test.sh
read file
if [ -e "$file" ]
then
echo "asfsafafa"
else
echo "NO SUCH FILE"
fi
#

After changing to [ -e "$file" ], it is working. Make sure there is a space between [ and -e.

Cheers,

1 Like

yea got it friends :slight_smile:

---------- Post updated at 01:46 AM ---------- Previous update was at 01:33 AM ----------

friends one more question

read file >> $file.csv 

is it correct we can make a new file with same file name ?
and my read file is also .csv

change your code to

read file
touch $file

If file is already present how you can make new file with same file name.
You should decide either you want create new file or append data into old file.

You can append data to that file
using

echo "data" >> $file

OR create new file

echo "data" > $file

and if your file name is having csv in it then you don't need to use $file.csv
and if you want to add extension use $file".csv"

I hope this helps :slight_smile:

pamu

1 Like

You can also try this if you are checking for a regular file in below way.

#!/bin/sh
read file
if [ -f $file ]
then
echo "asfsafafa"
else
echo "NO SUCH FILE"
fi