1752340 Members
5911 Online
108787 Solutions
New Discussion юеВ

check file

 
neocosmic
Occasional Contributor

check file

1. how to use file command to check a file whether is binary file or C object files?

2. how can we insulate a variable from any chracter that may follow it
2 REPLIES 2
Stanley_8
Advisor

Re: check file

you can use the command "find"
ex:find / -type b|wc -l
Here are the usage as follows.

-type c True if the type of the file is c, where c is
one of:
f Regular file
d Directory
b Block special file
c Character special file
p FIFO (named pipe)
l Symbolic link
s Socket
n Network special file
M Mount point
Stuart Browne
Honored Contributor

Re: check file

1) You have to trap the output of the command, and compare it against a string or regular expression in some manner.

e.g.

MYFILE=/path/to/file
if [ "$(expr "$(file ${MYFILE})" : '.*: \(.*\)')" = "ASCII C program text" ]
then
echo "C code"
fi

lets break this down a bit.

The core of this is the 'file' command:

file ${MYFILE}

This executes the 'file' command on the file listed above, in this case '/path/to/file'.

If it's C source code, it will return something like this:

/path/to/file: ASCII C program text

We then pass this as an argument to the 'expr' command:

expr "/path/to/file: ASCII C program text" : '.*: \(.*\)'

This will do some regular expression pattern matching, breaking it up at the space after the : (Regular Expressions are a whole different topic!). It returns the string after the space, so this will return:

ASCII C program text

We then use the 'if' command to check the final output.

Throughout this, I use the $() inbuilt bash function to launch sub-shells to execute the commands inline. This is an easy way to get the STDOUT of one command into a variable, or other things, such as here - an argument to another command.

This is one method to do what you are asking. You should hopefully be able to get a few ideas of other ways to do this.

2) The example above shows you how to do this. It's the ${} method of referencing variables:

${MYNAME}

Example:

$MYNAMEis = a variable called 'MYNAMEis'

${MYNAME}is = the contents of variable 'MYNAME' followed directly by the word is.

The variable referencing like this also has many other functions in bash and ksh usage. The above example could be written differently, like this:

MYFILE=/path/to/file
MYTYPE=$(file ${MYFILE})
if [ "${MYTYPE#*: }" = "ASCII C program text" ]
then
echo "C code"
fi

This isn't all that portable however, only working on "Bourne Again" and "Korn" shells, but it is possible.

Shell scripting is fun stuff isn't it? :)


Also, I've noticed that over the last few days that you've been asking a fair number of questions. How about showing your thanks by assigning some points to the many people who've taken time out to give you a hand. I'm sure they'd appreciate it.
One long-haired git at your service...