否则运行 shell 的脚本在放入函数内时表现异常

Otherwise functioning shell script behaves abnormally when put inside a function

为了学习,我尝试修改了一个 shell 脚本,该脚本将工作空间作为参数,如果没有给出参数则提示用户。 我想到了这个:

getWorkspaceFromUser() {
    while true; do
        read -e -p "Is current directory your workspace? (y/n): " input_yn
        case $input_yn in
            [Yy]* )
                workspace="."
                break
                ;;
            [Nn]* )
                while true; do
                    read -e -p "Please enter the path to your workspace (use tabs)? " input_ws
                    if [ -d $input_ws ]; then
                        workspace=$input_ws
                        break
                    fi
                    echo "Please enter a valid directory. "
                done
                break
                ;;
            * ) echo "Please answer yes or no."
                ;;
        esac
    done
    echo $workspace
}

# check if a valid workspace was provided. Otherwise, get it from user.
if [ $# -gt 0 ] && [ -d  ]; then
    workspace=
else
    workspace=$(getWorkspaceFromUser)
fi

#...... rest of the
#...... processing follows

如果我在第一个提示中输入了 y/n 以外的字符,或者如果我在第二个提示中输入了无效路径,我会看到异常行为。例如:

Is current directory your workspace? (y/n): k
Is current directory your workspace? (y/n): k
Is current directory your workspace? (y/n): k
Is current directory your workspace? (y/n): y
Please answer yes or no. Please answer yes or no. Please answer yes or no. .

Is current directory your workspace? (y/n): n
Please enter the path to your workspace (use tabs)? gggg
Please enter the path to your workspace (use tabs)? gggg
Please enter the path to your workspace (use tabs)? gggg
Please enter the path to your workspace (use tabs)? /home
Please enter a valid directory. Please enter a valid directory. Please enter a valid directory. /home

令人费解的是,如果我将 getWorkspaceFromUser() 的内容保存为 shell 脚本并 运行 它,它会按预期工作。有谁知道这里发生了什么?谢谢

你基本上都在做:

echo "Please answer yes or no."
echo $workspace

并假设 bash 将确定哪些是为用户准备的,哪些是为捕获准备的。

相反,您应该将所有状态消息写入标准错误:

echo >&2 "Please answer yes or no."
...
echo >&2 "Please enter a valid directory. "

这样它们就会出现在屏幕上,而不是出现在您的 workspace 变量中。