I am working on a shell script that takes a single command line parameter, a file path (might be relative or absolute). The script should examine that file and print a single line consisting of the phrase:
Windows ASCII
if the files is an ASCII text file with CR/LF line terminators, or
Something else
if the file is binary or ASCII with “Unix” LF line terminators.
currently I have the following code.
#!/bin/sh
file=$1
if grep -q "\r\n" $file;then
echo Windows ASCII
else
echo Something else
fi
It displays information properly, but when I pass something that is not of Windows ASCII type through such as /bin/cat it still id's it as Windows ASCII. When I pass a .txt file type it displays something else as expected it is just on folders that it displays Windows ASCII. I think I am not handling it properly, but I am unsure. Any pointers of how to fix this issue?
Use
file
command to find out file type:As you specify you only need to differentiate between 2 cases, this should work.
As you have specified
#!/bin/sh
, OR if your goal is total backward compatibility, you may need to changewith
To use your script with filenames that include spaces, note that all
$
variable names are now surrounded with double-quotes. AND you'll also have to quote the space char in the filename when you call the script, i.e.Also, if you have to start discriminating all the possible cases that
file
can analyze, you'll have a rather large case statement on your hands. ANDfile
is notorious for the different messages it returns, depending on the the contents of/etc/file/magic
, OS, versions, etc.IHTH