我试图做一个shell脚本来添加和删除用户到文本文件。 我想使用args来比较是否删除或添加用户,但是无论我输入什么args,两个代码都可以运行,这是我的代码:
#!/bin/bash
arg1="$1"
arg2="$2"
if [ "$arg1"="add" ]; then
if ! grep -q $arg2 "users.txt"; then
sed -i -e 's/users:/users: \n - '$arg2'/g' users.txt
echo "user added: $arg2"
else
echo "user exists: $arg2"
fi
fi
if [ "$arg1"="del" ]; then
if grep -q $arg2 "users.txt"; then
sed -i -e 's/- '$arg2'//g' users.txt
echo "user $arg2 deleted"
else
echo "not found $arg2"
fi
fi
这是我的文本文件users.txt
:
users:
- angel
- rick
在终端上运行sh addUser.sh add user1
:
user added: user1
user user1 deleted
在终端上运行sh addUser.sh del user1
:
user added: user1
user user1 deleted
结果是一样的,我该如何解决?
答案 0 :(得分:0)
感谢@melpomene的建议
问题是[ "$arg1"="add" ]
中的空格
将[ "$arg1"="add" ]
更改为[ "$arg1" = "add" ]
,即可正常使用。
#!/bin/bash
arg1="$1"
arg2="$2"
if [ "$arg1" = "add" ]; then
if ! grep -q $arg2 "users.txt"; then
sed -i -e 's/users:/users: \n - '$arg2'/g' users.txt
echo "user added: $arg2"
else
echo "user exists: $arg2"
fi
fi
if [ "$arg1" = "del" ]; then
if grep -q $arg2 "users.txt"; then
sed -i -e 's/- '$arg2'//g' users.txt
echo "user $arg2 deleted"
else
echo "not found $arg2"
fi
fi