1

Question: Script will receive any number of file names as arguments. Script should check whether every argument supplied is a file or directory. If directory report. If file, then name of the file plus number of lines present in it should be reported.

Below is my code,

#!/bin/sh
for i in $*; do
    if [ -f $i ] ; then
       c=`wc -l $i`
       echo $i is a file and has $c line\(s\). 
    elif [ -d $i ] ; then
    echo $i is a directory. 
    fi
done

Output:

shree@ubuntu:~/unixstuff/shells$ ./s317i file1 file2 s317h s317idir
file1 is a file and has 1 file1 line(s).
file2 is a file and has 2 file2 line(s).
s317h is a file and has 14 s317h line(s).

My question: Variable c's value are 1 file1, 2 file2, 14 s317h on every iteration. Whereas I'd want it to 1,2 and 14. Why does it contain the former values and not the latter one? Where am I wrong?

Note: s317i is my file name and file1 file2 s317h and s317idir are the command line arguments.

Kindly advice.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 2
    "Why does it contain the former values" - just try typing `wc -l some_file` on the console and you'll see why. I suspect that's not the question you want to ask though. – Mat Oct 27 '13 at 07:20
  • Try `c=\`cat $i|wc -l\`` so that wc has no file name to print. – Diego Basch Oct 27 '13 at 07:27

1 Answers1

3

That's the output of the wc command. For example:

$ wc -l file1
1 file1

However if you redirect stdin from file1 or pipe the stdout of another command into wc then it won't give you the filename.

$ wc -l < file1
1
$ cat file1 | wc -l
1

Hence your script should read as follows:

#!/bin/bash

for arg in $@; do
    if [ -f $arg ]; then
        echo $arg is a file and has `wc -l < $arg` lines.
    elif [ -d $arg ]; then
        echo $arg is not a file, it is a directory.
    fi
done

Note that I'm using bash instead of sh and $@ instead of $*.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • 2
    Just a little thing : If you use the "test" external or his fork "[" instead of the "[[" internal KSH/Bash instruction, you must protect your variables with doubles quotes. See http://stackoverflow.com/a/19598570/2900196 to get more details. – Idriss Neumann Oct 27 '13 at 09:33