I have a simple question. I want to execute a C program in a shell script. How do I do that? Thanks for your help in advance.
-
1It should be possible just by putting the program's name on the line. What have you tried and what happened?FrustratedWithFormsDesigner– FrustratedWithFormsDesigner2011-05-11 20:09:09 +00:00Commented May 11, 2011 at 20:09
-
3This question is either too simple or too complex. Please provide an example of what you want to do. All of what goes on in a shell script involves calling C programs.user2100815– user21008152011-05-11 20:09:34 +00:00Commented May 11, 2011 at 20:09
-
2Not executing any C program in a shell script would be more challenging ...jlliagre– jlliagre2011-05-11 20:30:32 +00:00Commented May 11, 2011 at 20:30
-
It's worth noting that you execute a C program in a shell script in exactly the same way as you would if you were executing it yourself in the shell, in the same context that that line of the shell script would be in (same directory, same environment, etc.).Robin Green– Robin Green2011-05-11 22:07:58 +00:00Commented May 11, 2011 at 22:07
-
@Chris Lutz: I didn't wrote impossible and anyway, exit, being part of the shell itself, is likely to be written in C.jlliagre– jlliagre2011-05-12 05:33:29 +00:00Commented May 12, 2011 at 5:33
3 Answers
cc hello_world.c #produces a.out
./a.out #run your program
IMHO, your problem is the $PATH. Your current directory is not in PATH, so when you enter
a.out
your shell respond:
-bash: a.out: command not found
you should execute it as
./a.out
(or add "." to your PATH, but this is not recommended.)
Comments
Almost every program that you execute in a shell script is a C program (but some, often many, of the commands you execute may be built into the shell). You execute a C program in the same way as any other program:
- By basename:
command [arg1 ...]- The command must be in a directory searched by the shell - on your PATH, in other words.
- By relative name:
./command [arg1 ...]or../../bin/command [arg1 ...]- The program must exist and be executable (by you)
- By absolute name:
/some/directory/bin/command [arg1 ...]- The program must exist and be executable (by you)
One of the beauties of Unix is that programs you create, whether in C or any other language, attain the same status as the system-provided commands. The only difference is that the system-provided commands are in a different place (such as /bin or /usr/bin) from commands you create (such as usr/local/bin or $HOME/bin).