Sourced Bash Variables Not Working in Conditional Statements


Posted on May 12, 2016 in Development

The other day I was writing a bash script to make automatic backups of MongoDB. I had the main backup script ( and an options file ( options.cfg). The idea was that would be committed to the project’s repository, while would be a local file, not added to the repo, because it might contain sensitive information such as database authentication details, FTP login details, AWS keys, etc.

Simplified, the two files looked something like this:


But the conditional statement for the FTP backup wouldn’t run despite the option being enabled in the options file. I thought that maybe I had a syntax error somewhere, so I checked it dozens of times, but everything seemed to be in order. I wasn’t getting any errors either.

I thought that perhaps the options file wasn’t being sourced properly, so I added echo $FTPBACKUP line into the file and it correctly printed it out in the console. It was really confusing.

Only when I declared the sourced variable in the file with declare -p FTPBACKUP, did I realize that something was wrong. Instead of printing declare -- FTPBACKUP="yes" as you would expect, the script was printing "eclare -- FTPBACKUP="yes. Turns out that the options.cfg file, which I was editing in Sublime text, had DOS line endings which caused the issue above. You can test whether that’s the case by running cat -t options.cfg. If it prints out something like

you have the same problem.

Resolving it is rather simple. You can use dos2unix on the file or simply run sed -i -e 's/\r$//' options.cfg. This will fix the line endings and the variables will be sourced correctly.

Enjoyed this post? Share it with others.
Email this to someoneShare on FacebookShare on Google+Tweet about this on Twitter

Leave a reply

Your email address will not be published. Required fields are marked *