echo - 语法错误:错误的替换

时间:2013-12-02 08:25:47

标签: linux bash

有问题的脚本:

  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

但输出:

name.sh: 13: Syntax error: Bad substitution

请帮忙,谢谢 我将非常感激:))

2 个答案:

答案 0 :(得分:10)

以下一行:

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

导致Syntax error: Bad substitution,因为您使用bash执行脚本。您要么使用导致错误的shdash执行脚本。


编辑:为了修复您的脚本以使其能够与shdash一起使用bash,您可以替换以下行:

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

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

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

答案 1 :(得分:2)

使用纯BASH功能取出所有不必要的expr调用:

#!/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"