bash - Bash 脚本语法错误:文件意外结束
问题描述
我正在尝试创建一个简单的 bash 脚本来在 ubunutu 上创建和删除用户,这是我的脚本
sudo nano createuser.sh
#!/bin/bash
choice=2
# Main Display
echo "Enter Number to select an option"
echo
echo "1) Add User"
echo "2) Delete User"
echo
while [ $choice -eq 2 ]; do
read choice
if [ $choice -eq 1] ;
then
echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd $user_name -m -p $user_passwd
cat /etc/passwd
else if [$choise -eq 2] ; then
cat /etc/passwd
echo -e "Enter Password"
read del_passwd
echo -e "User to be deleted:"
read del_user
sudo userdel -r $del_user
cat /etc/passwd
echo
fi
我不确定我的脚本是否有错字,或者其他什么。每当我执行脚本时,我都会收到此消息
输入数字以选择一个选项
- 添加用户
- 删除用户
./createuser.sh:第 31 行:语法错误:文件意外结束
预先感谢您的帮助 !!
解决方案
错误:
- 错误
if/else/fi
的顺序,你所拥有的基本上就是这几个错误
if [ ]
then
# something
else
if [ ]
then
# something else
fi
# fi should be here ti close outer if []
- 在bash中你已经
if then/elif/else
关闭了fi
所以像这样的东西
if []
then
# something
elif []
then
# something else happened
else
# something else than elif happened
fi
;
afterif []
,它只有在if
和than
在同一行时才会出现,就像这样
if [] ; then
# something
elif []
# something else happened
else
# something else than elif happened
fi
- 测试括号内的空间
[]
if [ a -eq 5 ]
# ^ ^
# +-------+----< notice space here
- 在 bash
while
序列中如下所示while [ ] do done
。喜欢以下
while [ i -le 55 ]
do
# do something
done
建议
- 用于
-s
在 bash 中读取密码以在键入时隐藏它。
结论,上面的所有修复都是工作脚本:
#!/bin/bash
choice=2
# Main Display
echo "Enter Number to select an option"
echo
echo "1) Add User"
echo "2) Delete User"
echo
while [ $choice -eq 2 ]
do
read choice
if [ $choice -eq 1 ]
then
echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd $user_name -m -p $user_passwd
cat /etc/passwd
elif [ $choise -eq 2 ]
then
cat /etc/passwd
echo -e "Enter Password"
read del_passwd
echo -e "User to be deleted:"
read del_user
sudo userdel -r $del_user
cat /etc/passwd
echo
else
echo "Wrong option you have 1 or 2"
fi
done
推荐阅读
- javascript - 如何在不使用 setTimeout() 的情况下使代码在 x 时间后执行
- python - 角色可以有不同的属性吗?(烧瓶 SQLAlchemy)
- node.js - 如何使 MongoClient 在 node js rest API 的所有页面中全局可用
- javascript - codeandbox.io 无法读取 null 的属性“addEventListener”
- offset - TimeScaleDB 连续聚合刷新策略结束偏移未按预期工作
- python - 循环中数据框的嵌套动态变量
- excel - 命令栏“工作簿选项卡”如何自动选择
- ruby-on-rails - 无法使用 yarn + webpacker + Ruby on Rails 6 获取包
- sql - SQL - 如何检查所有可用日期是否存在数据?
- python - 如何从 url 下载 facebook 图片