Linux.com

C take input from Bash Script

Link to this post 30 Nov 10

Hi,

I make a simple c file which takes input from user and then display it. I am trying to make a bash script in which i predefined those input and then run the c program inside bash and the c program takes the input which i have defined (i.e. user don't need to enter the input)

Here is the code.


#include<stdio.h>
void main()
{
char ch;
int num;
printf("Enter a single character:\n");
scanf("%c", &ch);
printf("Enter any number:\n");
scanf("%d", &num);

printf("You type charachter %c\n", ch);
printf("You type number %d\n", num);
}

And here is the bash file

#!/bin/bash

ch=s

num=2

./test < $ch $num

When i run the bash script it don't take the input values of ch and num. then i find on Google to use | so i tried ./test | $ch $num but didn't work

Please help me.


Thank you

Link to this post 03 Dec 10

./test << EOF
$ch
$num
EOF

Link to this post 2 days ago

What you did in your bash script is correct, but you might as well write "./test s 2"
In fact, when bash encounter '$varname', it replace it first with the value of the variable varname, before the function call, so the line is converted to "./test s 2" before bash calls the c file, which is the moment when ./test s 2 is converted to an array with tree pointer to "./test\0", "s\0" and "2\0".
This array can be acceded by defining main like "int main (int argc, char ** argv)"
(argc and argv are named by convention, but there types ca not be changed)
argv is the array bash where bash putted the words of the line that called the c file.
You can then access to 's' and '2' with argv[1][0] and argv[2][0].
The next thing you might want to do is convert 2 in an integer, so you might find this (http://stackoverflow.com...convert-string-to-integer...) usefull.

Who we are ?

The Linux Foundation is a non-profit consortium dedicated to the growth of Linux.

More About the foundation...

Frequent Questions

Join / Linux Training / Board