Echo - Syntax error: Bad replacement

A script with the problem:

  1 #!/bin/bash
  2
  3 skl="test"
  4 # get length
  5 leng=$(expr length $skl)
  6 # get desired length
  7 leng=$(expr 22 - $leng)
  8
  9 # get desired string
 10 str=$(printf "%${leng}s" "-")
 11
 12 # replace empty spaces
 13 str=$(echo "${str// /-}")
 14
 15 # output
 16 echo "$str  obd: $skl  $str"
 17

but it produces:

name.sh: 13: Syntax error: Bad substitution

Please help, thanks. I would be very grateful :)

+4
source share
2 answers

Next line:

str=$(echo "${str// /-}")

results in Syntax error: Bad substitutionbecause you are not running your script with bash. You execute your script with shor dash, which causes an error.


EDIT: in order to fix your script so that it works with shand dashin addition to bash, you could replace the following lines:

# get desired string
str=$(printf "%${leng}s" "-")

# replace empty spaces
str=$(echo "${str// /-}")

from

str=$(printf '=%.0s' $(seq $leng) | tr '=' '-')
+5
source

Take out all unnecessary expr calls using pure BASH functions:

#!/bin/bash

skl="test"
# get length
leng=${#skl}
# get desired length
leng=$((22 - leng))

# get desired string
str=$(printf "%${leng}s" "-")

# replace empty spaces
str=$(echo "${str// /-}")

# output
echo "$str  obd: $skl  $str"
+1
source

All Articles