Bash: ${string:$i:1} 这是什么意思?

-1 linux bash reverse substring

这是脚本。它反转用户输入的字符串:

#!/bin/bash
read -p "Enter string:" string
len=${#string}
for (( i=$len-1; i>=0; i-- ))
do
# "${string:$i:1}"extract single single character from string.
reverse="$reverse${string:$i:1}"
done
echo "$reverse"
Run Code Online (Sandbox Code Playgroud)

我不明白脚本的以下部分。这是什么?看起来像是某种扩展变量插值。

${string:$i:1}
Run Code Online (Sandbox Code Playgroud)

Chr*_*aes 5

在 bash 中做这样的事情: ${string:3:1} 表示:从 pos 3 处的字符开始(从 0 开始,所以是第 4 个字符),并且长度 = 1 个字符。

例如:

string=abc
Run Code Online (Sandbox Code Playgroud)

然后 ${string:0:1} 等于a${string:2:1} 等于c

此脚本获取变量的值$i:因此它只获取位置处的字符$i


Sub*_*beh 5

这是子串扩展。

从手册页:

   ${parameter:offset:length}
          Substring  Expansion.   Expands  to up to length characters of parameter starting at the character specified by offset.  If length is omitted, expands to the
          substring of parameter starting at the character specified by offset.  length and offset are arithmetic expressions (see ARITHMETIC  EVALUATION  below).   If
          offset evaluates to a number less than zero, the value is used as an offset from the end of the value of parameter.  Arithmetic expressions starting with a -
          must be separated by whitespace from the preceding : to be distinguished from the Use Default Values expansion.  If length evaluates to a  number  less  than
          zero,  and  parameter  is  not @ and not an indexed or associative array, it is interpreted as an offset from the end of the value of parameter rather than a
          number of characters, and the expansion is the characters between the two offsets.  If parameter is @, the result is length positional  parameters  beginning
          at  offset.   If parameter is an indexed array name subscripted by @ or *, the result is the length members of the array beginning with ${parameter[offset]}.
          A negative offset is taken relative to one greater than the maximum index of the specified array.  Substring expansion applied to an associative  array  proâ
          duces  undefined  results.  Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expansion.
          Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1 by default.  If offset is 0, and the posiâ
          tional parameters are used, $0 is prefixed to the list.
Run Code Online (Sandbox Code Playgroud)