如何使用C在bash中实现逻辑运算符?

时间:2015-02-08 02:02:05

标签: c bash gnu logical-operators

我是C编程新手。我正在尝试用逻辑运算符编写一个简单的命令行解释器。它的工作原理如下:

command1 ; command2 || command3 && command4
if ; second command will be executed after first command
if || second command only be executed if first command failed
if && second command will only be executed if first one succeeded

例如:

echo one ; echo one || echo two && echo four

输出应如下所示:

  

一个

     

一个

     

4

任何提示都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

int command_execute(void){
int i;
int next = 0;
int previous = 0;
while(moperator >= 0){ //moperator recorded the numbers of logical operators
    if(execute(words[next], next)== 0){ //words stored the tokenize string 
        moperator--;                    
        for(i = previous; i < nwds; i++){
            if(!strcmp(cwords[i], ";")){ //cwrods is a copy of words  
                previous = i;
                next = i + 1;
                moperator--;
                break;
            }else if(!strcmp(cwords[i], "||")){
                continue;
            }else if(!strcmp(cwords[i], "&&")){
                moperator--;
                previous = i;
                next = i + 1;
                break;
            }
        }
    }else{
        for(i = previous; i < nwds; i++){
            if(!strcmp(cwords[i], ";")){
                previous = i;
                next = i + 1;
                break;
            }else if(!strcmp(cwords[i], "||")){
                previous = i;
                next = i + 1;
                break;
            }else if(!strcmp(cwords[i], "&&")){
                    continue;
                }
        }    
      }
    }
    return 0;
}

这是我写的用来执行命令的方法。通过消除空格来对输入进行标记化。