Thread: Array splicing and extracting

  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    93

    Array splicing and extracting

    Hello,

    I am looking for an easy way to splice an array (full of commands). It is an array full of commands and pipes for the bash shell

    Example, if I pass an array like the following into a function

    array[0] = "ls"
    array[1] = "-a"
    array[2] = "|"
    array[3] = "grep c"
    array[4] = "|"
    array[5] = "more"

    What I want to do is extract array[0] and array[1], and execute them into a child process etc (open a pipe and use dup2 etc), continue until I find a pipe and extract array[3], and continue onwards.

    Which string functions should I be using or simply an easier method. I have never been that good with C style strings and arrays.

    Typically, array[0] will always be a command

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Are you writing your own shell or something?

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Thankless task to write your own shell. It's probably a student task

    I would suggest that you could probably send the arguments as a list to some suitable version of "exec" - there are many variants - I think "execv" or "execve" is the function you'd want. Unless you are doing this on a Windows system (or other "non-unix"), in which case I have no good idea on how you do that. (Concatenate the whole lot with "strcat", adding spaces where needed, and do "system(mylong_string_of_commands);" perhaps?

    Edit: if you are using "exec", don't forget to do fork first...

    --
    Mats

  4. #4
    Registered User
    Join Date
    Nov 2004
    Posts
    93
    Yeah I know how to do the executing, I just need a little help on the array splicing first.

    Edit: Student lab

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by INFERNO2K View Post
    Yeah I know how to do the executing, I just need a little help on the array splicing first.
    But you DON'T NEED to splice the array to use execv[e], as it takes a list of arguments already split up - so all you need to do is decide what is the command ("ls") and what is the argument(s) to that command ("-l"), and pass that as argv[] to exec. That's the whole point of my suggesting that you use this function.

    --
    Mats

  6. #6

Popular pages Recent additions subscribe to a feed