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?

2
  • system("a=(a 9 8 4) ; echo ${a[*]}") Commented Jul 7, 2018 at 16:16
  • Hmm... why call bash? Most bash commands are implemented in C and you can call them directly using the C API... Commented Jul 7, 2018 at 16:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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[*]}'");.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.