bash 脚本并尝试理解 echo 命令

gst*_*uis 3 shell-script

我正在学习 bash 脚本,当我在我的脚本中处理某些内容时,我正在寻找为自己创建一个微调器时,我在这个问题中遇到了这段代码:

i=1
sp="/-\|"
echo -n ' '
while true
do
printf "\b${sp:i++%${#sp}:1}"
done
Run Code Online (Sandbox Code Playgroud)

这就是我一直在寻找的:不连接的微调器类型,只是擦除其条目并回显中的下一个字符 $sp

但是我不明白这是如何在

printf "\b${sp:i++%${#sp}:1}"
Run Code Online (Sandbox Code Playgroud)

有人可以为我详细说明一下,以便我了解发生了什么吗?从编程的角度来看,它看起来像一个三元 for 循环,但在sp:i++我迷路之后。我知道 1 意味着在$spvar 中只显示一个字符。

我也知道这while将永远结束。

另外值得一提的是,有几个不同echo而printf当我试着echo用echo "\b${sp:i++%${#sp}:1}"未提供相同的结果... 参考

roa*_*ima 5

这里有两个变量在起作用。你可以更清楚地看到这是怎么回事:

sp="abcd" i=0                                         # Initialisation
printf "%d %s %d\n" "$i" "${sp:i++%${#sp}:1}" "$i"    # Repeat this line a few times
Run Code Online (Sandbox Code Playgroud)

您看到的是每次使用该表达式时$i都会增加一 ( $i++)。取 取模 的长度$sp,作为字符串的起始索引$sp。所以 when $iis 6, then 6 % 4is 2so$sp打印的第三个字符(字符串偏移量从零开始)

你可以像这样解压表达式,

sp="abcd" i=0
len_sp=${#sp}              # length of $sp

i=$(( i + 1 ))             # increment $i
mod_i=$(( i % len_sp ))    # wrap around length of $sp
sp_sub=${sp:mod_i:1}       # get substring of one character
printf "%s" "$sp_sub"      # print it
Run Code Online (Sandbox Code Playgroud)

其他有趣的部分是echo -n ' ',它打印一个没有尾随换行符的空格,以及printf "\b",它打印一个退格。