1

For my homework I need to write an alias that checks if a given file is regular and readable. The problem i am getting is that if i include else if or elif i get this error...

-bash: syntax error near unexpected token `else'

here is my code...

alias getname='read filename'

alias vfile='getname; if [ ! -f $filename ]; then echo "Irregular file"; (exit 1); elif [ ! -r $filename]; then echo "Not readable"; (exit 2); fi;'

I need to use an else if so that if there is an error only one statement will be printed.

I am aware that a shell function or script would be more practical but for the assignment I have to use an alias. I am still very new to UNIX so any help will be very much appreciated.

edit: I do have to use an alias, it is a file name that you give (a static file) and even when I change outelse if for elif I still receive the syntax error I described in the question.

EDIT2: I found the problem, I removed the fi; before the elif statement but now i receive a missing ']'error.

  • 1
    What does your code look like when you include the else? – Timothy Martin Oct 12 '17 at 23:55
  • You are using else if, but the correct syntax is elif. – nxnev Oct 13 '17 at 0:02
  • even when i use elif i still get the syntax error – mike Oct 13 '17 at 0:04
  • Do you strictly have to use alias? Which version of Bash are you using? – nxnev Oct 13 '17 at 0:07
  • I'm not sure you are going to be able to accomplish your task. Do you need to check if a static file is regular and readable or if a given file is? Because I don't think alias's support positional parameters. – Jesse_b Oct 13 '17 at 0:07
1

So this worked for me:

alias vfile='read -p "Enter the filename: " MY_FILE; if [ ! -f $MY_FILE ]; then echo "Irregular file"; (exit 1); elif [ ! -r $MY_FILE ]; then echo "Not readable"; (exit 2); fi'

EDIT I see what you did there =)

Just for readability here is the command broken out:

alias vfile='read -p "Enter the filename: " MY_FILE; \
if [ ! -f $MY_FILE ]; then \
echo "Irregular file"; \
(exit 1); \
elif [ ! -r $MY_FILE ]; then \
echo "Not readable"; \
(exit 2); \
fi'

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.