【问题标题】:How to implement logical operator in bash using C?如何使用 C 在 bash 中实现逻辑运算符?
【发布时间】:2015-02-08 02:02:04
【问题描述】:

我是 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

输出应如下所示:

一个

一个

四个

任何提示将不胜感激。

【问题讨论】:

  • 显示你迄今为止尝试过的内容

标签: c bash gnu logical-operators


【解决方案1】:
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;
}

这是我编写的用于调用执行命令的方法。输入已通过消除空格进行标记。

【讨论】:

  • 为什么你不能直接把这个添加到你的问题中而不是把它作为答案?
猜你喜欢
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 2011-09-10
  • 1970-01-01
相关资源
最近更新 更多