1

I have following file, where i want to increment the versioncode:

version=$(<versioncode.txt)
echo "$version"
version=$((version+1))
echo "$version"
echo $version >  versioncode.txt

This file is called "test.sh". On the commandline i ran following: "bash test.sh". The output and the error is this:

niklasraab@DESKTOP-BLJGB4D:/mnt/c/Flutter/src/hapii$ bash test.sh
1
")syntax error: invalid arithmetic operator (error token is "
1
niklasraab@DESKTOP-BLJGB4D:/mnt/c/Flutter/src/hapii$

Problem is that i am getting the "invalid arithmetic operator" error. I am running this project on windows. With bash subsystem ubuntu installed.

Niklas Raab
  • 1,576
  • 1
  • 16
  • 32

2 Answers2

1

When Bash creates this error message it does something very similar to `printf 'syntax error: invalid arithmetic operator (error token is "%s")\n' "$token". For that to end up as

")syntax error: invalid arithmetic operator (error token is "

(the 1 lines are from your echos) your file must contain a carriage return (\r) character, so it ends up printing syntax error: invalid arithmetic operator (error token is ", then moving to the start of the line (which is what carriage return does), and finally printing ") there.

To make this work you should extract the current version number from the file, printf '%s' "$version" > versioncode.txt to clean up the file, and use that command in your script (instead of echo) to ensure the format of that file.

l0b0
  • 55,365
  • 30
  • 138
  • 223
  • 1
    The problem was, that the bash script itself was formated with DOS endings. The data was correct. In VS Code you can switch by clicking CRLF in the bottome appbar and then selecting LF. This solved the problem. Also thanks to @I0b0, your info helped a lot. Just started with Bash sorry for not looking into the wiki. Next time I will! – Niklas Raab Nov 19 '18 at 21:07
1

I just did this in my own windows linux subsystem and it seemed to work:

nellis@L-X-NELLIS:~$ echo 1 >> versioncode.txt
nellis@L-X-NELLIS:~$ cat versioncode.txt
1
nellis@L-X-NELLIS:~$ version=$(($(cat versioncode.txt)))
nellis@L-X-NELLIS:~$ echo "$version"
1
nellis@L-X-NELLIS:~$ version=$((version+1))
nellis@L-X-NELLIS:~$ echo "$version"
2
nellis@L-X-NELLIS:~$ echo $version >  versioncode.txt
nellis@L-X-NELLIS:~$ cat versioncode.txt
2
Nick Ellis
  • 1,048
  • 11
  • 24