AKIWEB
AKIWEB

Reputation: 19612

counter=$ unexpected in the shell script

I have below lines in my shell script.

#!/bin/bash

counter=0
counter=$((counter+1))
echo $counter

And I need to run the above shell script like this-

sh -x test.sh

Whenever I try to run the above script, I awlays get error as -

`counter=$' unexpected

Any suggestions what changed I need to make there?

Updated Script:

#!/bin/bash

counter=0
counter=$(($counter+1))
echo $counter

Upvotes: 0

Views: 1602

Answers (4)

jlliagre
jlliagre

Reputation: 30823

I wouldn't suggest reverting to an outdated syntax.

Using sh -x test.sh is defeating your scripts's shebang #!/bin/bash. You force sh to be used as the interpreter to parse your script instead of /bin/bash. Up to Solaris 10 included, /bin/sh is the original bourne shell with pre POSIX syntax. It shouldn't be used but in legacy scripts.

You can then simply state a shell that understands your syntax, i.e. one of:

/usr/xpg4/bin/sh -x test.sh

or

/bin/bash -x test.sh

or

/bin/ksh -x test.sh

Should you really want sh -x test.sh to work as is, just switch to the POSIX mode by setting your path like this:

PATH=/usr/xpg6/bin:/usr/xpg4/bin:$PATH

Upvotes: 0

Chris Seymour
Chris Seymour

Reputation: 85795

Try:

#!/bin/sh

counter=0
counter=`expr $counter + 1`
echo $counter

$ sh -x test.sh

+ counter=0
++ expr + 1
+ counter=1
+ echo 1
1

Upvotes: 1

anubhava
anubhava

Reputation: 785196

Looks like you have an older version of sh. Try using following script:

#!/bin/bash

counter=0
counter=`expr $counter + 1`
echo $counter

Upvotes: 1

cnicutar
cnicutar

Reputation: 182649

Try using bash instead of sh since $(( ... )) isn't standard.

Upvotes: 2

Related Questions