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 '15 at 22:18
  • 1
    shellcheck.net might help you find some problems too – chicks Dec 16 '15 at 1:06

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.

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.