bash - 如何从 STDIN 获取字符串输入并将其保存在 bash 中的变量中以在脚本的其他部分使用它
问题描述
我正在尝试编写一个脚本,它将在 linux (ubuntu) 服务器上创建一个新用户。我是脚本编写新手,我遇到了问题
如何从用户输入中读取变量并在脚本的其他部分使用该变量
这就是我所拥有的,但在执行过程中陷入困境。谢谢。
update_pkgs() {
echo "
----------------------
Prerequisites : Making sure everything is up to date
----------------------
"
# checks is all pkgs are up to date
sudo apt-get update -y
# installing necessary pkgs
sudo apt-get install build-essential libssl-dev -y
}
create_user() {
echo "
----------------------
1. Creating a new user with name `<user>` and gives correct access.
----------------------
"
# [ASK]: How to make <user> a variable I read from STDIN
# and pass it around in the following commands
# add new user with the name of `user`
sudo adduser --ingroup www-data --disabled-password <user>
# copy ssh/ folder from `ubuntu` user to new user
# and gives the right permissions/privileges
sudo cp -R .ssh/ /home/<user>/
sudo chown -R <user>:www-data /home/<user>/.ssh/
}
# 1. asks to run the script
echo "
----------------------
Do You Wish to run this Script ?
----------------------
"
select yn in "Yes" "No" create quit; do
case $yn in
Yes)
update_pkgs();
create_user();
break;;
No) exit;;
create)
read -p "Enter name of user: " user
create_user($user)
quit)
break;;
*)
echo 'Invalid option $REPLY'
esac
done
解决方案
bash
总是按顺序运行命令,除非你告诉它在后台运行命令。
您可以在此处查看如何将标准输入保存到变量中。
推荐阅读
- flutter - flutter clean 不清理任何东西/也不显示错误
- python - 用于灵活创建日期时间范围的 Python 函数
- html - 在特定位置绘制/放置元素到 SVG 图像上
- nginx - VPS 上的 Laradock 尝试访问域时出现 HTTP ERROR 500 错误
- flutter - Flutter Provider 和 sqflite 集成
- java - 如何使用事件来计算重复事件的结束日期
- java - 如何从具有条件的多对多关系中选择实体
- javascript - 如何等待 Subject.next
- java - Tomcat Servlet Logger 不打印所有内容
- javascript - “此交互失败”除了此错误,我根本找不到问题