否则,当放入函数时,正常运行的shell脚本会出现异常行为

时间:2015-08-12 19:44:12

标签: shell zsh

为了学习,我尝试修改一个以工作空间作为参数的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 $1 ]; then
    workspace=$1
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脚本并运行它,它会按预期工作。有谁知道这里发生了什么?感谢。

1 个答案:

答案 0 :(得分:2)

你基本上都在做两件事:

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

并假设bash将确定哪个是针对用户的,哪个是用于捕获。

相反,您应该将所有状态消息写入stderr:

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

这样他们就会在屏幕上而不是workspace变量中结束。