Shell Commands in Objective-C

Discussion in 'Mac Programming' started by RevK, Aug 18, 2008.

  1. RevK macrumors member

    Joined:
    Apr 26, 2004
    #1
    Hello MacRumors;

    I have been working on a few projects in Objective-C recently and have found it extremely difficult (if not impossible) to run a shell command/script from the code.

    I have found this code for running a shell script from the resources folder:
    Code:
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/sh"];
    [task setArguments:[NSArray arrayWithObjects:[[NSBundle mainBundle] pathForResource:@"sscript" ofType:@"sh"], nil]];
    [task launch];
    The only thing is that I'd like to be able to use type the command right into the code; for example:

    touch /Users/myusername/Desktop test.txt

    Any help would be greatly appreciated, Thanks!
     
  2. Cromulent macrumors 603

    Cromulent

    Joined:
    Oct 2, 2006
    Location:
    The Land of Hope and Glory
  3. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #3
    or system()? (which forks, but does other things like invoking a shell to run your command, etc.)
     
  4. Cromulent macrumors 603

    Cromulent

    Joined:
    Oct 2, 2006
    Location:
    The Land of Hope and Glory
    #4
    Ah balls, I always get them mixed up. Yes system() would be a better function to use.
     
  5. Catfish_Man macrumors 68030

    Catfish_Man

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #5
    Easy. Save the script to a temporary file and run that, or (I don't recall if sh/bash accepted input from stdin) pipe to stdin.
     
  6. RevK thread starter macrumors member

    Joined:
    Apr 26, 2004
    #6
    Would saving to a temporary file be as efficient as using system()?

    I've heard bad things about using system().

    Would way would be best for some simple commands?
     
  7. Cromulent macrumors 603

    Cromulent

    Joined:
    Oct 2, 2006
    Location:
    The Land of Hope and Glory
    #7
    What exactly?
     
  8. RevK thread starter macrumors member

    Joined:
    Apr 26, 2004
    #8
    From another forum post I found:


    "You could use system() but it's use is proscribed.

    NSTask would be the proper API supported method of doing it."
     
  9. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #9
    From the system() man page:
    Code:
    STANDARDS
         The system() function conforms to ISO/IEC 9899:1990 (``ISO C90'') and is
         expected to be IEEE Std 1003.2 (``POSIX.2'') compatible.
    I'm more confident in that staying the same than NSTask.

    -Lee
     
  10. RevK thread starter macrumors member

    Joined:
    Apr 26, 2004
    #10
    I tried using system() in a test project and it works great!

    Thanks for showing me. You all are really awesome.
     

Share This Page