首页 > 解决方案 > 如何在 bash 脚本`read`中强制没有空格?

问题描述

这是我在 bash 脚本中的函数

function add_github_token_with_alias(){

  while [ -z $alias ]
  do
    echo -en "\n"
    read -p "An alias to name your token (or press Ctrl+C to cancel): " alias
  done

  while [ -z $token ]
  do
    echo -en "\n"
    read -p  "Token (or press Ctrl+C to cancel): " token
  done
}

当我运行它时,它看起来像这样

An alias to name your token (or press Ctrl+C to cancel): a new one
/opt/digitalocean/github_tokens_setup.sh: line 18: [: too many arguments

Token (or press Ctrl+C to cancel): abc

Is the information correct? [Y/n]

有没有办法阻止用户在他们的回复中提交空格?我应该怎么写?

标签: bash

解决方案


感谢@WilliamPursell 的评论,我知道该怎么做

我添加了

if [[ "$alias" =~ \  ]]; then
      echo "No spaces allowed!" >&2
      unset alias
fi

按照建议在 while 语句中检查输入和“$alias”

function add_github_token_with_alias(){

  while [ -z "$alias" ]
  do
    echo "\n"
    read -p "An alias to name your token (or press Ctrl+C to cancel): " alias
    if [[ "$alias" =~ \  ]]; then
      echo "No spaces allowed!" >&2
      unset alias
    fi
  done

  while [ -z "$token" ]
  do
    echo "\n"
    read -p  "Token (or press Ctrl+C to cancel): " token
    if [[ "$token" =~ \  ]]; then
      echo "No spaces allowed!" >&2
      unset token
    fi
  done
}

推荐阅读