4

I have commands in a bash script getting data from a source text file and then adding the value of a variable to it and using it in an if/else condition.

Source data file (db_count.ini) (Note: contains a space at the inside the double quotes):

db_ctdy_sr=" 7"

Script:

source db_count.ini

# Removing the whitespace on the stored data
n_db_sr=${db_ctdy_sr// /}

# Sum
c=0
b=7

echo "Value of db:"$n_db_sr

sm=$((n_db_sr + c))

echo "The value of db:"
echo "$sm" 
echo $sm 

if [ "$sm" = "$b" ]
then
   echo "Success."
else
   echo "Not."
fi

echo "Bye!"

But when I run the script it always me this

The value of db:7
") Syntax error Invalid arithmetic operator (error token is "
The value of:


Not.
Bye!

Any tips? Any suggestions?

Thanks!

  • I can only get close to your error when I mangle the db_ctdy_sr assignment, for example: db_ctdy_sr=" 7\"" -- can you confirm the exact syntax that db_count.ini is using? – Jeff Schaller Jul 21 '16 at 13:07
  • @JeffSchaller, check my post again sir I had update some of the codes changing $a to $sm – Edmhar Jul 22 '16 at 0:22
  • @JeffSchaller , Inside the db_count.ini you can see a variable named db_ctdy_sr=" 7" – Edmhar Jul 22 '16 at 0:24
3

Your script is working here. The only way to make it produce the same error you report is to make the variable db_ctdy_sr contain a new line:

Add a new line:

source db_count.ini
db_ctdy_sr=$' 7\r'

And then test the script:

$ ./so

Value of db:7
")syntax error: invalid arithmetic operator (error token is "
The value of db:
 //test if working
//test if working
Not.
Bye!

That could happen if the file db_count.ini contains DOS carriage return characters.

Execute:

$ sed -n l db_count.ini
db_ctdy_sr= 7\r$

(or similar) to see the \r in the file.

remove carriage returns by editing the file and removing the failing characters, or by changing this line:

n_db_sr=${db_ctdy_sr// /}

To:

n_db_sr=${db_ctdy_sr//[ $'\r'}]}

Or, more general to remove all control characters:

n_db_sr=${db_ctdy_sr//[ $'\001'-$'\037']}

To make sure the collating order will not modify the intended order of ascii values from 1 (octal 001) to 31 (octal 037), set the bash variable:

shopt -s globasciiranges

Available since bash version 4.3.

  • CR is decimal 13 but octal $'\015' or hex $'\xD' -- and bash $' ' also supports more convenient \r. – dave_thompson_085 Jul 22 '16 at 6:16
  • @dave_thompson_085 Yes, you are right; thanks, included. – user79743 Jul 22 '16 at 6:23

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.