bash - 如何在 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]
有没有办法阻止用户在他们的回复中提交空格?我应该怎么写?
解决方案
感谢@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
}
推荐阅读
- php - 未定义的属性:Illuminate\Database\MySqlConnection::$Id
- heroku - 是否可以在 Heruku 帐户之间的 circleci 中分离环境?
- javascript - GSTR-1 GSTR-2 GSTR-3B 的 JSON 格式是什么?
- python - 如何修复这个数组总和?
- amazon-web-services - AWS上的“WebSocket连接到...失败”,但在本地工作
- javascript - Handlebars - 处理 UTM 参数的最佳实践
- python - dunder 方法 __getitem__ 和 __len__ 如何提供迭代?
- c# - 如何在 Azure 函数方法中使用 JWT 验证?
- makefile - 在这种情况下如何用 grub 加载用户空间?
- php - 雄辩的关系:: 尝试在 null 上读取属性“product_price”