红联Linux门户
Linux帮助

bash shell的问题,请高手指点

发布时间:2011-08-23 10:40:52来源:红联作者:gwssgc
最近在看bash shell, 准备照猫画虎自己写个查询添加的小脚本,想实现的功能是:用户输入一个字符串然后查找passwd是否有这个字符串,如果有输出字符串,如果没有则把这段字符串添加到passwd。我想用if来判断用户输入的字段是否在passwd存在,但是实在想不出来如何实现。 如果不用if只是判断用户输入的字段是否存在,这样可以实现:
read -p "please input :" b
cat passwd | grep "$b" || echo "thiere is no "$b" in this file!"
但是如果想加入if判断语句是要把这些都写在[]里面么?还是有什么更简单的方法可达成?
文章评论

共有 4 条评论

  1. linvex 于 2011-09-03 15:51:53发表:

    你怎么不试试这样:
    read -p "please input:" b
    u=`cat passed | grep -c "$b"`
    if [ ”$u" = 1 ];then
    echo $b
    else
    echo "there is no “$b" in this file!"
    echo " “$b" will be add into passwd !"
    "$b" >> passwd
    fi
    貌似我们没改什么,但是这样更适用于多线程运行,你可以想象一下,我们在查找时往往都是猜不到的,这样一改,可以减少cpu的运算量,就是所谓的优化程式

  2. hhbh1991 于 2011-09-03 14:35:50发表:

    我觉得上面两种蛮好的,可以学习下

  3. gwssgc 于 2011-08-23 16:48:47发表:

    [i=s] 本帖最后由 gwssgc 于 2011-8-23 16:51 编辑 [/i]

    感谢LS,不过用你的方法程序不能成功运行。我是这么实现的

    #!/bin/bash
    read -p "please input:" b
    u=`cat passed | grep -c "$b"`
    if [ ”$u" = 0 ];then
    echo "there is no “$b" in this file!"
    echo " “$b" will be add into passwd !"
    "$b" >> passwd
    else
    echo $b
    fi

  4. zenghuan88 于 2011-08-23 15:56:18发表:

    或许可以这样写:
    read -p "please input :" b
    if [ -z `cat passwd | grep "$b"` ] # 如果字符串为空,则说明在passwd里不存在 $b
    then
    echo "thiere is no "$b" in this file!"
    exit 0
    fi