Expanding a relative path to a full path when running a C program in shell
Question
I have a problem when my script needs to communicate with a C executable. I cannot get the script's full path, which I need to load and send to another process.
The script's name is myScript
#!/home/user/git/proyect/test
hello this
is a
script
and this is the source code of the C executable
#include <stdio.h>
int main (int argc, char *argv[]){
int count;
printf ("Este programa fue llamado con: \"%s\".\n",argv[0]);
if (argc > 1){
for (count=1; count<argc; count++){
printf("argv[%d] = %s\n", count, argv[count]);
}
}
else{
printf("The command had no other arguments.\n");
}
return 0;
}
If I run myScript
from terminal,
argv[0]
shows the executable's path (I guess that's because it's the info at#!
).argv[1]
shows the first argument passed to the executable, i.e.- if I use
./myScript
as the argument, that is what I see (the relative path) - if I use
/home/user/git/proyect/test/scriptFolder/myScript
as the argument, it shows the absolute path (which is what I need, but I don't want to write the full path in terminal every time)
- if I use
So my question is, how do I get the full path of myScript
without passing its full path when calling the script?
Solution
Your question is not very well worded so I am not sure I am answering the same question that you are asking, but you can convert "./myScript" to its full path using the realpath() function.
OTHER TIPS
As i understand you are implementing a script parser/interpreter.
The main
function you present here is compiled and linked to the /home/user/git/proyect/test
executable. Am i right?
That means that when you execute ./myScript
on the terminal what is actually executed is /home/user/git/proyect/test ./myScript
.
If this is the case @MK's answer is right. And with realpath()
you can get the absolute path of "./myScript"
I would suggest editing your question to be more readable.