如何使用 Bash shell 脚本存储 C 程序的输出

How to store the output of C program using Bash shell scripting

这是我的 C 程序

int main(){

int n;
while(1){
    printf("Enter n:\n");
    scanf("%d",&n);
    switch(n){
        case 1: int t; 
            scanf("%d",&t);
            if(t<10)
            printf("true");
            else printf("false");
            break;
        case 2: char c;
            scanf("%c",c);
            if(c=='a') printf("true");
            else printf("false");
            break;
        case -1: break;
    }
        if (n==-1) break;   
}

return 0;
}

这是我的bashshell脚本

./a.out << 'EOF'
1
4
2
b
-1
EOF

这将执行代码但不保存输出

./a.out > outputfile

以上代码会保存输出,包括"Enter n".

我想执行代码并只保存 true/false 部分(即排除所有其他 printf)。如何存储文件的输出并为其提供输入?

./a.out < input.txt > output.txt

我为 a.out 制作了一个替代品,我可以将其用于测试。 is_odd.sh 查找奇数:

#!/bin/bash

exitfalse() {
   echo $*
   echo false
   exit 1
}

exittrue()
{
   echo $*
   echo true
   exit 0
}

[ $# -eq 0 ] && exitfalse I wanted a number
[[  =~ [0-9]+ ]] || exitfalse Only numbers please
((  % 2  == 0 )) && exitfalse Even number
exittrue Odd number

使用这个冗长的脚本会产生很多垃圾

#!/bin/bash
testset() {
   for input in john doe 1 2 3 4; do
      echo "Input ${input}"
      ./is_odd.sh "${input}"
   done
}

testset

你怎么能有相同的输出并且在一个文件中只有 false/true? 使用 tee 将输出发送到屏幕和一些将进行过滤的进程:

testset | tee >(egrep "false|true" > output)

我认为上面的命令最适合你的问题,我希望看到输入字符串:

testset | tee >(egrep "Input|false|true" > output)