从 /bin/sh 个函数返回
Returning from /bin/sh Functions
我已经写了很多 Bash,但我现在需要将我的一些代码移植到 /bin/sh
,我观察到奇怪的行为。
我有一个功能:
path_exists() {
path="" && shift
echo "$PATH" | tr ':' '\n' | while read path_entry ; do
test "$path" = "$path_entry" && return 0
done
return 1
}
我是这样称呼它的:
if path_exists "/usr/bin" ; then
echo "it exists"
else
echo "it does not exist"
fi
如果我 运行 它与 set -x
,我看到 return 代码被覆盖:
+ path_exists /usr/bin
+ path=/usr/bin
+ shift
+ echo /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
+ tr : \n
+ read path_entry
+ test /usr/bin = /usr/local/sbin
+ read path_entry
+ test /usr/bin = /usr/local/bin
+ read path_entry
+ test /usr/bin = /usr/sbin
+ read path_entry
+ test /usr/bin = /usr/bin
+ return 0
+ return 1
+ echo it does not exist
为什么我的函数不遵守我的 return 代码?
Why is my function not respecting my return codes?
因为管道产生了一个子shell,而你只是从一个子shell返回。同理:
echo | exit 0
不会退出您的 shell,只会从 | { the subshell on the right side of pipe; }
退出。或者以同样的方式 func() { ( return 1; echo 123; ); return 0; }; func
- return 1
只影响 subshell.
ash
、dash
和 bash
中的行为相同,但我认为 POSIX sh
中会是 unspecified.
Aaaa 无论如何:
path_exists() {
case ":$PATH:" in
*:"":*) ;;
*) false; ;;
esac
}
我已经写了很多 Bash,但我现在需要将我的一些代码移植到 /bin/sh
,我观察到奇怪的行为。
我有一个功能:
path_exists() {
path="" && shift
echo "$PATH" | tr ':' '\n' | while read path_entry ; do
test "$path" = "$path_entry" && return 0
done
return 1
}
我是这样称呼它的:
if path_exists "/usr/bin" ; then
echo "it exists"
else
echo "it does not exist"
fi
如果我 运行 它与 set -x
,我看到 return 代码被覆盖:
+ path_exists /usr/bin
+ path=/usr/bin
+ shift
+ echo /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
+ tr : \n
+ read path_entry
+ test /usr/bin = /usr/local/sbin
+ read path_entry
+ test /usr/bin = /usr/local/bin
+ read path_entry
+ test /usr/bin = /usr/sbin
+ read path_entry
+ test /usr/bin = /usr/bin
+ return 0
+ return 1
+ echo it does not exist
为什么我的函数不遵守我的 return 代码?
Why is my function not respecting my return codes?
因为管道产生了一个子shell,而你只是从一个子shell返回。同理:
echo | exit 0
不会退出您的 shell,只会从 | { the subshell on the right side of pipe; }
退出。或者以同样的方式 func() { ( return 1; echo 123; ); return 0; }; func
- return 1
只影响 subshell.
ash
、dash
和 bash
中的行为相同,但我认为 POSIX sh
中会是 unspecified.
Aaaa 无论如何:
path_exists() {
case ":$PATH:" in
*:"":*) ;;
*) false; ;;
esac
}