如何在 Bash 中逐字写入文件斜线分割字符串

How to write to file slash divided string word by word in Bash

我有一个字符串,例如/sd1/sd2/sd3/

我想用下一种方式写入文件

/sd1
/sd1/sd2
/sd1/sd2/sd3

我该怎么做?

注意:字符串的长度可能不同。即 /sd1/ 或 /sd1/sd2/sd3/sd4/sd5/

这个解决方案对我有用

string="/sd1/sd2/sd3/"

IFS='/' read -r -a sds <<< "$string"

tmpsd=""

for (( i=1; i<${#sds[@]}; i++ )); do

  tmpsd="${tmpsd}/${sds[i]}"

  echo ${tmpsd} >> file.txt

done