shell script to find file type

2019-09-07 09:35发布

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?

2条回答
老娘就宠你
2楼-- · 2019-09-07 10:09

Use file command to find out file type:

$ file /etc/passwd 
/etc/passwd: ASCII English text

$ file /bin/cat 
/bin/cat: Mach-O 64-bit executable x86_64

$ file test.txt 
test.txt: ASCII text, with CRLF line terminators
查看更多
混吃等死
3楼-- · 2019-09-07 10:25

As you specify you only need to differentiate between 2 cases, this should work.

#!/bin/sh
file="$1"
case $(file "$file") in
  *"ASCII text, with CRLF line terminators" )
     echo "Windows ASCII"
  ;;
  * )
     echo "Something else"
  ;;
esac

As you have specified #!/bin/sh, OR if your goal is total backward compatibility, you may need to change

$(file "$file")

with

`file "$file"`

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.

 myFileTester.sh "file w space.txt"
 OR
 myFileTester.sh 'file w space.txt'
 OR
 myFileTester.sh file\ w\ space.txt
 OR

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. AND file is notorious for the different messages it returns, depending on the the contents of /etc/file/magic, OS, versions, etc.

IHTH

查看更多
登录 后发表回答