2015-02-08 54 views
-1

我是C編程新手。我正在嘗試用邏輯運算符編寫一個簡單的命令行解釋器。它的工作原理是這樣的:如何使用C在bash中實現邏輯運算符?

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 

輸出應該是這樣的:

一個

一個

任何提示將不勝感激。

+0

顯示你到目前爲止嘗試過的東西 – 2015-02-08 02:18:15

回答

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; 
} 

這是我寫的調用執行命令的方法。輸入已經通過消除空白符號化了。

+1

爲什麼你不能使用只是把它添加到你的問題insteading把它作爲一個答案? – 2015-02-08 02:35:09