如何在POSIX shell脚本中迭代字符串的字符?

Lui*_*ire 4 shell posix sh dash-shell

符合POSIX的shell应提供这样的机制来迭代字符串集合:

for x in $(seq 1 5); do
    echo $x
done
Run Code Online (Sandbox Code Playgroud)

但是,如何迭代单词的每个字符?

Gor*_*son 6

这有点迂回,但我认为这适用于任何符合posix标准的shell.我已经尝试过了dash,但我没有繁忙的盒子来测试.

var='ab * cd'

tmp="$var"    # The loop will consume the variable, so make a temp copy first
while [ -n "$tmp" ]; do
    rest="${tmp#?}"    # All but the first character of the string
    first="${tmp%"$rest"}"    # Remove $rest, and you're left with the first character
    echo "$first"
    tmp="$rest"
done
Run Code Online (Sandbox Code Playgroud)

输出:

a
b

*

c
d
Run Code Online (Sandbox Code Playgroud)

请注意,不需要在赋值右侧的双引号; 我更喜欢在所有扩展中使用双引号,而不是试图跟踪它们离开它们的安全位置.另一方面,双引号[ -n "$tmp" ]是绝对必要的,first="${tmp%"$rest"}"如果字符串包含"*" ,则需要内部双引号.