1

I need to read some properties from a config file and execute some commands if the properties match certain values. But when I try to compare the value with a string in if condition, it doesn't work.

Below is a small version of what I am trying to do.

#!/bin/bash
source config.file

echo "mode: $mode"

if [ "$mode" = "slow" ];
then 
echo "Mode is slow"
fi

The config file looks like this.

###config###
mode=slow
user=admin
password=pwd
###end###

The echo statement prints the values as "slow" but the if condition is never satisfied. What am I doing wrong?

  • Use `bash -x yourscript` to run the script with debug logging enabled. If it says `[ $'slow\r' = slow ]`, f/e, that would confirm the DOS-line-endings diagnosis – Charles Duffy Jul 30 '21 at 12:32
  • BTW, `printf 'mode: %q\n' "$mode"` would do a better job of showing the actual value of `$mode` in an unambiguous form than `echo "mode: $mode"` does. Or if you really want to keep using `echo`, `echo "mode: <$mode>"` would at least make the specific problem clear (if you have that problem, the `>` would be printed at the front of the line, since a carriage return -- found in DOS newlines but not UNIX ones -- instructs the cursor to move all the way to the left). – Charles Duffy Jul 30 '21 at 12:35

1 Answers1

0

It works for me. Maybe you have MSWin line ends in the config file?

Run

dos2unix config.file

or

fromdos config.file

to convert them to the *nix standard.

choroba
  • 231,213
  • 25
  • 204
  • 289