running shell script using c program

7,547

Here is a fixed version of your code:

// Compile with:
// gcc     c-shellscript.c   -o c-shellscript

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

#define SHELLSCRIPT "\
printf 'Password Please:';\n\
stty -echo;\n\
read pass;\n\
stty echo;\n\
printf '\\n';\n\
sleep 2;\n\
echo $pass;"

int main()

{

  puts("Will execute sh with following script:");

  puts("---------");
  puts(SHELLSCRIPT);
  puts("---------");

  puts("Starting now");

  system(SHELLSCRIPT);

  return 0;

}

However, I don't think it is good practice to do things this way. It is also much much easier to create a separate shellscript file and just call that instead, even if you generate the shellscript file from within your code.

Have a look at these for more info:

Share:
7,547

Related videos on Youtube

Deepansh Kapoor
Author by

Deepansh Kapoor

Updated on September 18, 2022

Comments

  • Deepansh Kapoor
    Deepansh Kapoor over 1 year

    I wrote a script to hide user input during runtime it works as a simple script but i want to integrate into c program but gives following errors:

    warning: missing whitespace after macro name 
    
    error: expected ')' before 'Password' 
    

    can someone tell me what i'm doing wrong.

    Here's the c program:

    #include"header.h"
    #define SHELLSCRIPT"\
    #bin/bash\n\
    printf"Password Please:"\n\
    
    stty -echo\n\
    
    read pass\n\
    
    stty echo\n\
    
    printf'\n'\n\
    
    sleep"2"\n\
    
    echo "$pass"\n\
    
    "
    
    int main()
    
    {
    
    puts("Will execute sh with following script:");
    
    puts("SHELLSCRIPT");
    
    puts("Starting now");
    
    system(SHELLSCRIPT);
    
    return 0;
    
    }
    
    • KIAaze
      KIAaze about 8 years
      This is a programming question and is more appropriate for stackoverflow.com .
    • David Foerster
      David Foerster about 8 years
      Why do you even bother to write a C program if you end up running an Sh script anyway? That is not to say you can't change the echo state of the terminal in plain C. Alternatively you could use one of the existing programs that safely ask the user for a password.
  • ShadowRunner
    ShadowRunner over 6 years
    one advantage of using c to launch a script is that you can then set the c program as executable but not readable (the script still needs to be readable to be executed, but can be "hidden" somewhere else)