0

How can I programmatically run terminal command?

Now I'm doing like this:

-(IBAction)proceedTapped:(id)sender
{
NSLog(@"%@",[self runCommand:@"cd ~"]);
NSLog(@"%@",[self runCommand:@"ls"]);
}

-(NSString *)runCommand:(NSString *)commandToRun
{
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:
                      @"-c" ,
                      [NSString stringWithFormat:@"%@", commandToRun],
                      nil];

[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];


[task launch];


NSData *data;
data = [file readDataToEndOfFile];

NSString *output;
output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
return output;
}

For single commands this code works well, but in my case, when I want to change directory to ~(home) and then do 'ls' this doesn't work well (it looks like to run two commands in two different terminal windows). So how to run multiple commands like in one terminal window ? Thank you.

Paige DePol
  • 1,121
  • 1
  • 9
  • 23
arturdev
  • 10,884
  • 2
  • 39
  • 67
  • 1
    possible duplicate of [How to use NSTask run terminal commands in loop in consistent environment?](http://stackoverflow.com/questions/13217415/how-to-use-nstask-run-terminal-commands-in-loop-in-consistent-environment) – Martin R Jan 29 '14 at 09:15
  • Follow this http://stackoverflow.com/questions/19038364/nsprocessinfo-returns-different-path-than-echo-path/19050417#19050417 – Hussain Shabbir Jan 29 '14 at 09:56

1 Answers1

0

In one of my applications I have:-

- (IBAction)openDirInTerminal:(id)sender {  // context only
    DirectoryItem *item = (DirectoryItem *)[self.dirTree focusedItem];
    NSString *s = [NSString stringWithFormat:
                   @"tell application \"Terminal\" to do script \"cd \'%@\'\"", item.fullPath];
    NSAppleScript *as = [[NSAppleScript alloc] initWithSource: s];
    [as executeAndReturnError:nil];
}

DirectoryItem *item = (DirectoryItem *)[self.dirTree focusedItem]; is my method, but replace item.fullPath with a Path.

You could add the 2nd command to the script string (followed by a newline).

Milliways
  • 1,265
  • 1
  • 12
  • 26
  • What you have done is using applescript. This is not the one what questioner has asked he wants to use unix shell script. Follow this http://stackoverflow.com/questions/19038364/nsprocessinfo-returns-different-path-than-echo-path/19050417#19050417. – Hussain Shabbir Jan 29 '14 at 10:07
  • @HussainShabbir: Well, it uses AppleScript to run a shell script… – mipadi Jan 29 '14 at 22:38
  • He wants to use NSTask not NSApplescript. – Hussain Shabbir Jan 30 '14 at 02:45