You are not logged in.

#1 2008-10-28 20:15:05

kiepmad
Member
Registered: 2007-12-26
Posts: 41

Bash scripting, check filetype with file command

Hi community,

I've got as homework to write a script which uses the command file to check if a file is really a text file, and if yes echo its name.

I wrote the following

#!/bin/bash
for filetype in *
do
a= file $filetype | cut -f2 -d' '
b="ASCII"
    if [ "$a"="$b" ]
    then
        echo "$filetype"
    fi
done

however, this does not work.

It just echoes the filetype and all the filenames.

directory
Desktop
Bourne-Again
existe
gzip
kernel26-one-2.6.27-3-i686.pkg.tar.gz
Bourne-Again
list
Bourne-Again
pidof
empty
ps
Bourne-Again
realjpg
Bourne-Again
taille
ASCII
temp.txt
directory
themes

Any ideas?
Why is the filetype echoed, when I declare it as a variable?
Why does the condition thing not work?

Basically, what am I missing?

Offline

#2 2008-10-28 20:54:49

catwell
Member
From: Bretagne, France
Registered: 2008-02-20
Posts: 207
Website

Re: Bash scripting, check filetype with file command

Change:

a= file $filetype | cut -f2 -d' '

to:

a=$(file $filetype | cut -f2 -d' ')

Offline

#3 2008-10-28 20:57:16

Dieter@be
Forum Fellow
From: Belgium
Registered: 2006-11-05
Posts: 2,000
Website

Re: Bash scripting, check filetype with file command

Don't put a space after 'a='.  What you're doing there is just executing file and not capturing it's output (that's why you see it on the screen). You need to capture the output and store it in $a


< Daenyth> and he works prolifically
4 8 15 16 23 42

Online

#4 2008-10-28 20:59:30

Procyon
Member
Registered: 2008-05-07
Posts: 1,819

Re: Bash scripting, check filetype with file command

You had the right idea

a= file $filetype | cut -f2 -d' '
1. when assigning do not put spaces around =
2. you are collecting the output of the command, so use $( ), or backtick

if [ "$a"="$b" ]
when comparing in [ put spaces around =

Then it will work as expected.

Offline

#5 2008-10-30 05:31:59

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: Bash scripting, check filetype with file command

Googling for TLDP's bash scripting guide should be helpful.

Offline

#6 2008-10-30 18:58:27

kiepmad
Member
Registered: 2007-12-26
Posts: 41

Re: Bash scripting, check filetype with file command

thanks for the ressource.
here's the link
http://tldp.org/LDP/abs/html/

Thanks also for the answers, they were really helpful.


ok, I wanted to post another problem I had but while I was pasting my code in here I realised my mistake. tongue

Offline

Board footer

Powered by FluxBB