PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

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

 August 18, 2022     bash, c, output, sh, shell     No comments   

Issue

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 (i.e excluding all the other printf's). How to store the output of a file along with giving inputs to it?


Solution

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 teeto 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)


Answered By - Walter A
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing