Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The ';' character in the input is being misinterpreted

Tags:

c

shell

I wrote a program to split an input string using ';' as the terminator and print the part of the string that is after ';'. The program shows correct output whenever substring following ';' in the input string is not a valid terminal command but also prints command not found. On the other hand, it does not prints anything when the substring followed by ';' is a valid terminal command and executes the substring as a command , e.g. in case input "sjhjh;ls" it will execute ls command.

How do I get rid of the command not found part? Here is the code:

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

int main(int argc, char *argv[])
{
    char * input;
    char * str;
    char * word;
    char terminator = ';';

    if (argc < 2) {
         fprintf(stderr,"ERROR, no string provided\n");
         exit(1);
     }

     input = argv[1];
     word = strchr(input, terminator);
     if (word != NULL) printf("%s\n", word);
     return 0;
}
like image 584
Romy Avatar asked Jan 14 '17 07:01

Romy


1 Answers

When you execute your program like:

your_program_name sjhjh;ls

on the command line, you actually invoke two programs. The first is your_program_name sjhjh (so, argv[1] is "sjhjh"), and the second is ls. What you need is to make sure that the rest of the command line goes unparsed by the shell, and this is accomplished by properly quoting it:

your_program_name 'sjhjh;ls'
like image 171
DYZ Avatar answered Sep 24 '22 17:09

DYZ