如何使用C在bash中实现逻辑运算符?
问题描述:
我是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
输出应该是这样的:
一个
一个
任何提示将不胜感激。
答
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
显示你到目前为止尝试过的东西 – 2015-02-08 02:18:15