How to fix ~/.profile and ~/.bashrc syntax errors

This can happen if your files have a non-printing byte sequence at the start - for example a byte order mark - perhaps as a result of having edited them in a word processor program or Windows text editor.

For example, given

$ file profile bashrc
profile: UTF-8 Unicode (with BOM) text
bashrc:  UTF-8 Unicode (with BOM) text

(where profile and bashrc are local copies of my ~/.profile and ~/.bashrc with byte sequence 0xFE 0xFF inserted at the start) then

$ bash -c 'source profile; source bashrc'
profile: line 1: #: command not found
bashrc: line 1: syntax error near unexpected token `('
bashrc: line 1: `# ~/.bashrc: executed by bash(1) for non-login shells.'

The simplest fix is to use dos2unix, which removes the BOM by default:

$ dos2unix profile bashrc
dos2unix: converting file profile to Unix format...
dos2unix: converting file bashrc to Unix format...

$ file profile bashrc
profile: ASCII text
bashrc:  UTF-8 Unicode text

Or you can simply replace the files with fresh copies from the /etc/skel directory as you discovered (although obviously you will lose any customizations that way).


Other ways to check for non-printing bytes are

cat -A ~/.profile ~/.bashrc

in which a BOM will show up as a control sequence like M-oM-;M-?# or using xxd or od to examine the byte sequences directly

head -1 ~/.profile | od -tx1

xxd -l16 ~/.profile

The diff command is helpful insofar as confirming there is a difference, but not in identifying what the difference is:

$ diff profile ~/.profile
1c1
< # ~/.profile: executed by the command interpreter for login shells.
---
> # ~/.profile: executed by the command interpreter for login shells.

The easy way to check the user's shell...

If you don't have Users and Groups application already installed, install it this way...

sudo apt-get update

sudo apt-get install gnome-system-tools

Hit the Super key and type "Users", select Users and Groups application, click on the account name, then Advanced Settings, Advanced tab, and verify the correct Shell of /bin/bash.


Ubuntu 18.04.4 (automatic upgrade from 18.04.3 just a few weeks ago)
/bin/bash

I don't know what the problem was but this is the way I fixed it:

$ cd ~ 
$ which bash
/bin/bash  
$ mv .profile .profile.bak  
$ mv .bashrc .bashrc.bak  
$ cd /etc/skel/  
$ cp .profile ~/.profile  
$ cp .bashrc ~/.bashrc  

(Note: /bin/bash is the correct location for bash.)

Thanks everybody for your comments and assistance.