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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20323738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:30:21  来源:igfitidea点击:

echo - Syntax error: Bad substitution

linuxbash

提问by andrej

A script with a 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 outputs:

但它输出:

name.sh: 13: Syntax error: Bad substitution

please help, thanks I would be very grateful :)

请帮忙,谢谢我将不胜感激:)

采纳答案by devnull

The following line:

以下行:

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

is resulting into Syntax error: Bad substitutionbecause you are notexecuting your script using bash. You are either executing your script using shor dashwhich is causing the error.

导致Syntax error: Bad substitution因为您没有使用bash. 您正在使用shdash导致错误的脚本执行。



EDIT: In order to fixyour script to enable it to work with shand dashin addition to bash, you could replace the following lines:

编辑:为了修复您的脚本以使其能够与 一起使用sh并且dash除了 之外bash,您可以替换以下几行:

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

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

with

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

回答by anubhava

Take out all unnecessary expr calls, using pure BASH features:

使用纯 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"