HI guys

I need a shell script,from which i can read 1st line of every file present in the current directory.

thanks in advance

for i in `ls`
do
  head -1 ${i}
done

And I hope to God, that this is not homework assignment.

Or just:

head -1 *

I'm assuming he wanted to work with each line that he got, and even if not, that he didn't want the filename header before or the blank line after each line that head -1 * produces.

for i in `ls`
do
  head -1 ${i}
done

[...]

This is almost always the wrong way:
in this case:
1. you don't need to call external commands("ls")
2. you need to quote the varible (and you don't need braces ("{}"))
Your script will fail if the filenames contain spaces,
embedded new lines or other "pathological" characters,
consider this:

$ ls -l
total 4
-rw-r--r--   1 oracle   dba            2 Sep 14 07:54 file 2
-rw-r--r--   1 oracle   dba            1 Sep 14 07:53 file1
$ for i in `ls`
> do
>   head -1 ${i}
> done
file: No such file or directory
2: No such file or directory

So it's just:

$ ls -l
total 4
-rw-r--r--   1 oracle   dba            2 Sep 14 07:54 file 2
-rw-r--r--   1 oracle   dba            2 Sep 14 07:58 file1
$ for f in *;do head -1 "$f";done
2
1

I'm assuming he wanted to work with each line that he got, and even if not, that he didn't want the filename header before or the blank line after each line that head -1 * produces.

Not sure for that ...
...

And anyone doing that with filenames should be shot. And no you don't need the braces, but it is good form to keep them, and no, you do not need to quote the variable, unless there are spaces in the filename, which is bad form anyway, IMO.

Edit: And yes, I could have replaced `ls`with * in mine, as well, but then you have him asking "What does the * mean?", as well as anybody else looking at the script later who does not realise that you can use the * in that form at that location (which many people don't), so it is simply much clearer to call ls (and the cost, for a single instance anyway) is negligible.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.