Sloan Anderson Sloan Anderson - 1 month ago 6
C Question

How to send a string in bash script to a c program and use that string

I need to send a string to a C program using a bash script, and then take that string in the C program and do things to it. The issue is I can't figure out how to use the string. I tried printf to see what the c program actually got, and it printed out random numbers.

This is the bash script:

length=`/home/hellboy632789/linelength $line`;


This is the C Program:

int main(int argc, char *argv[])

{

int length;
char *string = argv[1];
for(length = 0; string[length] != '\0'; length++);
printf("%d\n", length);
return(0);
}


I am fairly new to C, but any help would be greatly appreciated.

Answer

You are returning the length of the string as the exit code of the C program. Bash makes that exit code available in the variable $?.

Your bash script, on the other hand, is putting into your "length" variable what your C program is printing to stdout, which is not at all the same thing.

Since the exit code is conventionally 0 if the program executed correctly, and non-zero if there was an error, it makes more sense to use the bash script as such and change the C code.

Replace return(length); with printf("%d\n", length);return(0); and your program should work as you wish. You can test by simply running /home/hellboy632789/linelength testtestwhatever at your bash command prompt.

Of course there are many other ways, but I suppose this is but a first step to something more complicated. Good luck and persevere.

EDIT: for example, this works:

~/316643$ cat linelength.c
#include <stdio.h>

int main(int argc, char *argv[])
{
    int length;
    char *string = argv[1];
    for(length = 0; string[length] != '\0'; length++);
    printf("%d\n", length);
    return(0);
}
~/316643$ gcc -o linelength linelength.c
~/316643$ ./linelength qwertyui
8
~/316643$ lorens@rush:~/316643$ line="qwertyui"
~/316643$ length=`./linelength "$line"`
~/316643$ echo "length is $length bytes"
length is 8 bytes
~/316643$ 
Comments