Gia*_*iac 3 linux bash substring sh
在此代码中:
#!/bin/sh
a='sdsdsd'
c=${a:0:1}
Run Code Online (Sandbox Code Playgroud)
我使用第二行逐一读取字符串的字节(在循环中),但它在 sh 中返回错误(“sh:3:错误替换”)。有什么办法可以在 sh 模式下做到这一点吗?由于某些原因我应该使用 sh (不是 bash,我知道 bash 没问题)
子字符串参数扩展不是POSIX shell 规范的一部分。这是一个 ksh/bash 功能。如果你需要它,你不能使用#!/bin/sh
如果您需要使用sh,您需要拨打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
Run Code Online (Sandbox Code Playgroud)