如何在BOURNE SHELL中通过分隔符拆分和迭代子串?

时间:2015-05-16 10:42:41

标签: string shell loops split sh

最近,我一直在尝试自定义位于Ubuntu ~/.profile的shell配置文件。我想做的一件事是:

# PATH-like variable containing paths separated by ':'
MY_ROOTS=/f/o/o:/b/a/r:/e/t/c
for some magic iterating my_root in $MY_ROOTS do;
    my_bin="$my_root/bin"
    # add it to PATH!
    [ -d "$my_bin" ] && {
        expr ":$PATH:" : ".*:$my_bin:.*" >/dev/null || PATH="${PATH:+"$PATH:"}$my_bin"
    }
done

因为它在.profile中,我需要iterating部分与Bourne Shell兼容。很多人都问过这样的问题,但我相信大多数解决方案看起来像 Bashism 。在我花了很多时间谷歌搜索后,我仍然没有找到合适的答案。我可以请你的意见吗?

1 个答案:

答案 0 :(得分:0)

尝试:

OIFS="$IFS"
IFS=:
MY_ROOTS=/f/o/o:/b/a/r:/e/t/c
for my_root in $MY_ROOTS; do
    # your code here with $my_root
done
IFS="$OIFS"