Bash 子脚本错误地将输入重定向到 /dev/null



我正在编写一个脚本来自动创建.gitconfig文件。

这是我的主脚本,它调用一个函数,该函数又执行另一个文件。

dotfile.sh

COMMAND_NAME=$1
shift
ARG_NAME=$@
set +a
fail() {
  echo "";
  printf "r[${RED}FAIL${RESET}] $1n";
  echo "";
  exit 1;
}
set -a
sub_setup() {
  info "This may overwrite existing files in your computer. Are you sure? (y/n)";
  read -p "" -n 1;
    echo "";
    if [[ $REPLY =~ ^[Yy]$ ]]; then
    for ARG in $ARG_NAME; do
      local SCRIPT="~/dotfiles/setup/${ARG}.sh";
      [ -f "$SCRIPT" ] && echo "Applying '$ARG'" && . "$SCRIPT" || fail "Unable to find script '$ARG'";
    done;
  fi;
}
case $COMMAND_NAME in
  "" | "-h" | "--help")
    sub_help;
    ;;
  *)
    CMD=${COMMAND_NAME/*-/}
    sub_${CMD} $ARG_NAME 2> /dev/null;
    if [ $? = 127 ]; then
      fail "'$CMD' is not a known command or has errors.";
    fi;
    ;;
esac;

git.sh

git_config() {
  if [ ! -f "~/dotfiles/git/gitconfig_template" ]; then
    fail "No gitconfig_template file found in ~/dotfiles/git/";
  elif [ -f "~/dotfiles/.gitconfig" ]; then
    fail ".gitconfig already exists. Delete the file and retry.";
  else
    echo "Setting up .gitconfig";
    GIT_CREDENTIAL="cache"
    [ "$(uname -s)" == "Darwin" ] && GIT_CREDENTIAL="osxkeychain";
    user " - What is your GitHub author name?";
    read -e GIT_AUTHORNAME;
    user " - What is your GitHub author email?";
    read -e GIT_AUTHOREMAIL;
    user " - What is your GitHub username?";
    read -e GIT_USERNAME;
    if sed -e "s/AUTHORNAME/$GIT_AUTHORNAME/g" 
    -e "s/AUTHOREMAIL/$GIT_AUTHOREMAIL/g" 
    -e "s/USERNAME/$GIT_USERNAME/g" 
    -e "s/GIT_CREDENTIAL_HELPER/$GIT_CREDENTIAL/g" 
    "~/dotfiles/git/gitconfig_template" > "~/dotfiles/.gitconfig"; then
      success ".gitconfig has been setup";
    else
      fail ".gitconfig has not been setup";
    fi;
  fi;
}
git_config

在控制台中

$ ./dotfile.sh --setup git
[ ?? ] This may overwrite existing files in your computer. Are you sure? (y/n)
y
Applying 'git'
Setting up .gitconfig
[ .. ]  - What is your GitHub author name?

然后我看不到我在输入什么...

dotfile.sh的底部,我将函数调用期间发生的任何错误重定向到/dev/null。但我通常应该看到我在输入什么。如果我从这一行中删除2> /dev/null sub_${CMD} $ARG_NAME 2> /dev/null;,它可以工作!!但我不明白为什么。

我需要这一行来防止我的脚本在我的命令不存在的情况下回显错误。我只想要我自己的消息。

例如

$ ./dotfile --blahblah
./dotfiles: line 153: sub_blahblah: command not found
[FAIL] 'blahblah' is not a known command or has errors

我真的不明白为什么我的子脚本中的输入被重定向到/dev/null因为我只提到 stderr 被重定向到 /dev/null .

谢谢

您的read语句中是否需要-e选项?

我在交互式外壳中进行了快速测试。 以下命令不回显字符:

read -e TEST 2>/dev/null

以下确实呼应字符

read TEST 2>/dev/null

相关内容

  • 没有找到相关文章

最新更新