Reputation: 554
I know that C program generally ends with return, where we return the status of the program. However, I want to return a string. The reason is that, I will be calling the C-executable from a shell script and printing the returned string. Is there any mechanism for the same ?
Upvotes: 4
Views: 4248
Reputation: 215517
You have to print the string to stdout
and use the shell's command substitution to read the result:
"`command`"
or:
"$(command)"
Either way, you should use the enclosing double-quotes as above. Note that this method has a potentially-serious problem that it removes all training newlines from the command's output. If you need to preserve the exact output, try:
output="$(command ; echo x)"
output="${output%x}"
Since OP mentioned that this is for a password, another piece of advice: once you've read a password into a shell variable, never pass it on the command line to other programs. Command lines are usually world-readable. Instead of something like
wget "http://$user:$pass@host/foo"
try something like
wget -i - << EOF
http://$user:$pass@host/foo
EOF
Here-files as in this example are useful with a number of programs which need to take passwords from scripts.
Upvotes: 0
Reputation: 7829
You cannot - you can only return an integer.
Remember that C was developed alongside Unix. Unix programs return an integer value which is intended as a status code. If a program was to return string(s) it would write them to stdout, and then the user (or a script) would pipe it into something useful.
MS DOS also had number-only status values.
Upvotes: 0
Reputation: 124760
You can't, but you don't need to either. You return a stat code from main, but you can always re-direct the output and capture it in your shell script.
Upvotes: 1
Reputation: 169318
Just output the string you want to return to standard output with printf
. Then in your script, do something like this:
SOMESTRING="`./yourprogram`"
The backticks will capture the output of the program, which will be the string you printed.
Upvotes: 4
Reputation: 76815
There is not way to return a string from main()
. Maybe the program itself should print the string ?
Upvotes: 5
Reputation: 26060
You cannot.
The best thing you could do is writing the string somewhere (on standard output, standard error or some file); then the shellscript will get your string from there.
Standard output (thus using just a printf
) is probably the best solution, since it will be very easy from your C program print the string, and very easy for the shellscript getting that data:
From shell script:
STRING="$( ./your_program argv1 argv2 )"
Upvotes: 5
Reputation: 799240
There is no such mechanism; the return code is expected to be a byte. If you want to output a string from your program then use something like printf()
and command substitution in the shell script to capture it.
Upvotes: 10