substring in sh returns "Bad substitution"

Viewed 3074

In this code:

#!/bin/sh
a='sdsdsd'
c=${a:0:1}

I use second line to read bytes of string one by one (in a loop), but it returns error in sh ("sh: 3: Bad substitution"). any way to do it in sh mode? for some reasons i should use sh (not bash, and i know bash will be OK)

2 Answers

The substring parameter expansion is not part of the POSIX shell specification. It's a ksh/bash feature. If you need it, you can't use #!/bin/sh

If you need to use sh, you need to call out to expr

$ dash -c '
    a="ABCDEF"
    i=1
    while [ "$i" -le "${#a}" ]; do
        c=$(expr substr "$a" "$i" 1)
        echo "$i:$c"
        i=$((i + 1))
    done
'
1:A
2:B
3:C
4:D
5:E
6:F

With posix shell without expr

#!/bin/sh
var='abcd'
count="${#var}"
until [ "$count" -eq 0 ];do
  vartemp="${var#[a-z]}"
  lavar="${var%$vartemp}"
  var="$vartemp"
  count="$((count-1))"
  echo "$var $count $lavar"
done
Related