I want to write a script that lists either the first n lines or the last n lines of a specified file.


if [ "$filename" == "head" ]

#If the user uses the head command then do the following.

then [ "$filename" == "tail" ]
        head -n 10 /MyDirectoryGoesHere
#If the user uses the tail command do this instead.

        tail -n 10 /MyDirectoryGoesHere

When I run this command I keep getting an error "Unexpected token near else" and I was told to add a for loop but don't know how or where. Appreciate the help.

  • I posted an answer about bash syntax for if constructs and case switches, but the real answer to this command is: just use the tail and head commands directly. They can already accept multiple files as arguments.
    – Wildcard
    Dec 15, 2015 at 22:18
  • 1
    shellcheck.net might help you find some problems too
    – chicks
    Dec 16, 2015 at 1:06

1 Answer 1


Three things:

(1) An if-then-else-fi construct should look more like this:

if [ "$myvar" = "value" ]; then
  # do stuff
elif [ "$myvar" = "othervalue" ]; then
  # do other stuff
  # do still other stuff

(2) You could just use a case switch:

case "$myvar" in
    # do stuff
    # do other stuff
    # do still other stuff

(3) I don't know what you're trying to do with the $1=filename commands, but it's definitely not the right way to do it, whatever it is. ;)

Check out the wooledge bash tutorial for more.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .