如何在 BOURNE SHELL 中通过分隔符拆分和迭代子字符串?
How to split and iterate substrings by delimiter in BOURNE SHELL?
最近我一直在尝试自定义位于 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。在我花了很多时间谷歌搜索之后,我仍然没有找到合适的答案。请问您有什么建议吗?
尝试:
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"
最近我一直在尝试自定义位于 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。在我花了很多时间谷歌搜索之后,我仍然没有找到合适的答案。请问您有什么建议吗?
尝试:
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"