How can i do this exercise in unix? Create the following command: lshead.bash – list the first few lines of every file in a directory specified by the argument. This command should also allow options to either list the first n lines or the last n lines of the files. Example command: lshead.bash –head 10 documents would list the first ten lines in every file in the documents directory.


This code gives the basic idea. You can add some features on your own, if want


function head_file()
    ls -p $cur_dir | grep -v / | while read file;do
        echo "First $1 lines of the FILE: $file"
        cat $file | head -n+$1 # Displaying the First n lines
        echo "*****************END OF THE FILE: $file**************"

function tail_file()
    ls -p $cur_dir | grep -v / | while read file;do
        echo "Last $1 lines of the FILE: $file"
        cat $file | tail -n+$1 # Displaying the last n lines
        echo "**************END OF THE FILE: $file******************"

case "$1" in
        head_file $2
        tail_file $2

        echo "Invalid Option :-("
        exit 1
exit 0
  • 1
    (1) Please don’t feed the bears, and please don’t do people’s homework for them when they’ve shown no sign of even trying to do it themselves.  (2) The first line should be #!/bin/bash — you left out the !.  (3) For clarity, you might want to change `…` to $(…) — see this, this, and this.  (4) There’s no need to say `pwd` or $(pwd) — you can get the current directory with $PWD.  … (Cont’d) – G-Man Nov 29 '15 at 20:50
  • (Cont’d) …  (5) If you define a function called head, then, whenever you say head, you will get that function, and not the head program.  Ditto for tail.  (6) cat filename | command is a useless use ofcat — don’t do it.  (7) You should always quote your shell variable references (e.g., "$cur_dir", "$file", "$1", and "$2") — unless you have a good reason not to, and you’re sure you know what you’re doing. – G-Man Nov 29 '15 at 20:50
  • Thanks Folks! for Negative Voting...I already said, that is basic idea....I knew shell scripting a little bit. I did concentrate on logic and basic idea and didn't on silly mistakes! – Veerendra Nov 30 '15 at 5:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.