简体   繁体   中英

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

This is my C program

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

This is my bash shell script

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

This will execute the code but doesn't save the output

./a.out > outputfile

The above code will save the output, including "Enter n".

I want to execute the code and save only true/false part (ie excluding all the other printf's). How to store the output of a file along with giving inputs to it?

I made an alternative for a.out, that I can use for testing. is_odd.sh looks for odd umbers:

#!/bin/bash

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

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

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

Using this verbose script gives a lot garbage

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

testset

How can you have the same output and only false/true in a file? Use tee to send output to the screen and to some process that will do the filtering:

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

I think above command fits best with your question, I would prefer to see the input strings:

testset | tee >(egrep "Input|false|true" > output)
./a.out < input.txt > output.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM