分页: 1 / 1
请大家帮助一下
发表于 : 2011-08-23 13:41
由 gwssgc
本人小菜一个,最近在看shell脚本, 准备照猫画虎自己写个查询添加的小脚本,想实现的功能是:输入一个字符串然后查找passwd是否有这个字符串,如果有输出字符串,如果没有则把这段字符串添加到passwd。我想用if来判断用户输入的字段是否在passwd存在,但是实在想不出来如何实现。 如果不用if只是判断用户输入的字段是否存在,应该可以这样实现:
read -p "please input :" b
cat passwd | grep -n "$b" || echo "thiere is no "$b" in this file!"
但是如果想加入if判断语句是要把这些都写在[]里面么?还是有什么更简单的方法可达成?请高手指点一下小弟。
Re: 请大家帮助一下
发表于 : 2011-08-23 14:46
由 wjchen
#!/bin/bash
read -p "please input :" b
num=`cat passwd | grep -c "$b"`
if [ $num -gt 0 ]; then
echo $b
else
echo $b >> passwd
fi
Re: 请大家帮助一下
发表于 : 2011-08-23 15:45
由 gwssgc
感谢LS的筒子,我怎么没想到呢!还要努力啊!

Re: 请大家帮助一下
发表于 : 2011-08-23 18:58
由 tusooa
为啥用if就要用[
代码: 全选
read -p "please input :" user
if grep -q "$user" passwd ; then
echo "$user"
else
echo "$user" >> passwd
fi
Re: 请大家帮助一下
发表于 : 2011-08-24 10:31
由 gwssgc
tusooa 写了:为啥用if就要用[
代码: 全选
read -p "please input :" user
if grep -q "$user" passwd ; then
echo "$user"
else
echo "$user" >> passwd
fi
呵呵,可能太‘教科书‘了吧

Re: 请大家帮助一下
发表于 : 2011-08-24 10:51
由 我就是我2
gwssgc 写了:tusooa 写了:为啥用if就要用[
代码: 全选
read -p "please input :" user
if grep -q "$user" passwd ; then
echo "$user"
else
echo "$user" >> passwd
fi
呵呵,可能太‘教科书‘了吧

使用[] 比较能够偷懒吧.一律使用[]
当然,这跟引用变量时的双引号是类似的, 使用 "$i" 能够处理变量中空格
对比下面两行代码
代码: 全选
i=1;if $i -gt 0 ;then echo i;else echo j;fi
i=1;if [ $i -gt 0 ];then echo i;else echo j;fi