Pro Q
Pro Q

Reputation: 5016

What is going on when I run a terminal/shell command in Swift?

I've spent a fair amount of researching how to run a particular terminal/shell command from within Swift.

The issue is, I'm afraid to actually run any code unless I know what it does. (I've had very bad luck with executing terminal code in the past.)

I found this question which seems to show me how to run commands, but I'm completely new to Swift and I'd like to know what each line does.

What does each line of this code do?

let task = NSTask()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "rm -rf ~/.Trash/*"]
task.launch()
task.waitUntilExit()

Upvotes: 1

Views: 378

Answers (2)

Pro Q
Pro Q

Reputation: 5016

As I was writing this question, I found I was able to find many of the answers, so I decided to post the question and answer it to help others like me.

//makes a new NSTask object and stores it to the variable "task"
let task = NSTask() 

//Tells the NSTask what process to run
//"/bin/sh" is a process that can read shell commands
task.launchPath = "/bin/sh" 

//"-c" tells the "/bin/sh" process to read commands from the next arguments
//"rm -f ~/.Trash/*" can be whatever terminal/shell command you want to run
//EDIT: from @CodeDifferent: "rm -rf ~/.Trash/*" removes all the files in the trash
task.arguments = ["-c", "rm -rf ~/.Trash/*"]

//Run the command
task.launch()


task.waitUntilExit()

The process at "/bin/sh" is described more clearly here.

Upvotes: 1

Code Different
Code Different

Reputation: 93151

  • /bin/sh invokes the shell
  • -c takes the actual shell command as a string
  • rm -rf ~/.Trash/* remove every file in the Trash

-r means recursive. -f means forced. You can find out more about these options by reading the man page in the terminal:

man rm

Upvotes: 3

Related Questions