1

I am trying to run some bash commands using C program,

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int j;
    char a[4]={'a','9','8','4'};
    for (j=0;j<=3;j++)
    {
        printf("a[%d]=%c      %p\n",j,a[j],&a[j]);
    }
    system("a=(a 9 8 4)");
    system("echo ${a[*]}");
}

In above code, below lines do not show anything

system("a=(a 9 8 4)");
system("echo ${a[*]}"); 

Any idea?

dhilmathy
  • 2,800
  • 2
  • 21
  • 29

2 Answers2

6

Two things:

  • each time you call system() a new shell will be invoked. That means variable declarations will only be visible to the currently invoked shell, not in subsequent calls to system()

  • besides that, system() internally calls /bin/sh, not /bin/bash. /bin/sh is on many systems (like yours) a link to a POSIX compliant shell. Array definitions are unfortunately not part of the POSIX shell language.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
3

system usually runs a POSIX shell (often dash, not bash) and each invocation starts a new shell process, so if you really want to start bash from system and have the second bash command print the array defined in the first, you need something like system("bash -c 'a=(a 9 8 4); echo ${a[*]}'");.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142