/bin/sh Need to identify file content type

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


/bin/sh Need to identify file content type



I'm working on busybox and have only /bin/sh available.
I would like to understand if the file I'm processing with my script are to be treated as ASCII (just read and do what I need to do) or gzip (so unzip first then do what I need to do).



The "file" command here would be perfect, but unfortunately it's just not available, hence I don't know what procedure to call as the input file I'm processing can be either format.



I'm wondering if there's a simple workaround I'm missing here to find this out...





What do you consider "non-ASCII"? Do you just need to test if your file has no characters with values outside 0-127?
– Charles Duffy
13 mins ago





You could check for the same magic number file looks for (IOW, make your own file that can only tell if a file is "gzip or not gzip")
– Sorpigal
6 mins ago





BTW, whether file is available is completely orthogonal to whether you're using /bin/sh -- it's a command that's provided by your operating system, not your shell.
– Charles Duffy
3 mins ago


file


/bin/sh




1 Answer
1



Implicit in your question is that you have a gunzip command, and are trying to figure out whether you need to invoke it.


gunzip



One command that can tell you that... is gzip.


gzip


contents_of_file() {
if gzip -t <"$file" >/dev/null 2>&1; then
gunzip -c <"$file"
else
cat <"$file"
fi
}



That said, you can also ask grep if a file has no non-printable, non-whitespace characters:


grep


is_plain_text() {
if grep -q -e '[^[:graph:][:space:]]' <"$1"; then
echo "$1 has non-ASCII characters"
else
echo "$1 is plain text"
fi
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

C# - How to create a semi transparent or blurred backcolor on windows form

Will Oldham

Makefile test if variable is not empty