Curtis Chong Curtis Chong - 1 month ago 15
Linux Question

unexpected token fi in bashrc

I was editing some environmental variables when I encountered this error:

bash: /home/splacorn/.bashrc: line 115: syntax error near unexpected token `fi'
bash: /home/splacorn/.bashrc: line 115: ` fi'


This if-statement-block is causing the issue but I don't see any unexpected characters and it's breaking my bashrc. I've tried removing the space in front of the fi but it still doesn't work. How do I fix this? Thanks.

if ! shopt -oq posix; then
if [ -f /usr/share/bash-completion/bash_completion ]; then
. /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
fi
. /etc/bash_completion
fi

Answer

Shell, unlike other programming languages you may be familiar with, does not allow empty blocks. In your code,

if [ -f /usr/share/bash-completion/bash_completion ]; then
  . /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
   #HERE
fi

you must put at least one command where I have marked #HERE.

In this case, it appears to me that the problem is that the fi and the following line have gotten swapped, i.e. the code is meant to read

if [ -f /usr/share/bash-completion/bash_completion ]; then
  . /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
  . /etc/bash_completion
fi

In the general case, if you need an empty block for some reason, the conventional thing to put in there is a single :, which is the shortest and most efficient way to write a no-op command in shell. For instance

if grep -q particular_setting /etc/daemon.conf; then
  :
else
  sed -i -e '$a\
particular_setting=true
' /etc/daemon.conf
fi

(In a portable shell script you can't use if ! ... so you have to write do-unless-condition constructs this way. That's obviously not a concern in a bash rc file.)

Comments