【发布时间】:2014-08-21 21:01:50
【问题描述】:
下面的 Bourne shell 脚本,给定一个路径,应该测试路径的每个组件是否存在;然后设置一个仅包含实际存在的组件的变量。
#! /bin/sh
set -x # for debugging
test_path() {
path=""
echo $1 | tr ':' '\012' | while read component
do
if [ -d "$component" ]
then
if [ -z "$path" ]
then path="$component"
else path="$path:$component"
fi
fi
done
echo "$path" # this prints nothing
}
paths=/usr/share/man:\
/usr/X11R6/man:\
/usr/local/man
MANPATH=`test_path $paths`
echo $MANPATH
运行时,它总是不打印任何内容。使用set -x 的跟踪是:
+ paths=/usr/share/man:/usr/X11R6/man:/usr/local/man
++ test_path /usr/share/man:/usr/X11R6/man:/usr/local/man
++ path=
++ echo /usr/share/man:/usr/X11R6/man:/usr/local/man
++ tr : '\012'
++ read component
++ '[' -d /usr/share/man ']'
++ '[' -z '' ']'
++ path=/usr/share/man
++ read component
++ '[' -d /usr/X11R6/man ']'
++ read component
++ '[' -d /usr/local/man ']'
++ '[' -z /usr/share/man ']'
++ path=/usr/share/man:/usr/local/man
++ read component
++ echo ''
+ MANPATH=
+ echo
为什么最后的echo $path 是空的? while 循环中的 $path 变量在每次迭代中增量设置就好了。
【问题讨论】:
-
/bin/sh通常只表示符合 POSIX 的 shell,不一定(甚至通常)不是真正的 Bourne shell。
标签: function shell return-value sh