1

I have seen similar posts in stackoverflow and other sites but I cannot find solution to my problem.

I have the following consoleout.sh file:

#!/bin/sh

#this way works in c:
#echo "Hello World!"

#but in function does not work:
a(){
  echo "Hello World!"
}

Following C code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    system(".  consoleout.sh"); 

    system("a");
    return 0;
}

Without system("./consoleout.sh"), it works fine.

Azeem
  • 7,094
  • 4
  • 19
  • 32

2 Answers2

4

system() invokes a shell and waits for it to terminate. Another call to system() will create a different shell that starts from scratch.

To run your shell function, you need to do it from the shell where it was defined:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    return system( ".  consoleout.sh; a" ); 
}
PSkocik
  • 52,186
  • 6
  • 79
  • 122
3

Each system calls a new instance of the shell, the second one doesn't know anything about the functions defined in the first one. You can, though, call the function in the first shell:

system(". consoleout.sh ; a");
choroba
  • 200,498
  • 20
  • 180
  • 248