unix script to opena valid file

March 15, 2011 at 12:45:28
Specs: unix
currently i am prompting a user for a file to edit in vi
however, it will open anything. I dont want to be able to opena binary file or a
directory. How could i use the command file with grep to accomplish this or i there a better way
ths is what i have


if [ 'grep " $file"' ]

then

echo "found file"
vi $file
else
echo "creating a valid .txt file for editing"

vi $file.txt


See More: unix script to opena valid file

Report •

#1
March 15, 2011 at 14:20:25
A way using the korn shell: check out the unix file command which determines the file type. I decided that any output from the file command containing 'ascii' or 'script' is a valid file - might be different in your world:

#!/bin/ksh

file="text.txt"
if [[ -a "$file" ]]
then # file exists
   if  [[ ( -r "$file" ) && ( -w "$file") ]]
   then # read and writable
       file "$file" |egrep "ascii|script"
       if [[ $? -eq 0 ]]
       then # ascii or script
          vi "$file"
       else
          echo "probably binary"
       fi
   fi
else
   echo "creating $file text file"
   vi "$file"
fi


Report •
Related Solutions


Ask Question