1

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()
Pro Q
  • 4,391
  • 4
  • 43
  • 92
  • 2
    Most of the time, by the way, it's preferable to spawn an explicit argv *without* involving a shell; here, however, you're relying on the shell to do globbing for you (expanding the `*` into a list of filenames before invoking `rm`). – Charles Duffy Mar 20 '17 at 21:26
  • (expanding the `~` into the user's home directory is also a job that the shell is doing in present case, and would need to be replaced if you were trying to do without it). – Charles Duffy Mar 20 '17 at 21:27

2 Answers2

3
  • /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
Code Different
  • 90,614
  • 16
  • 144
  • 163
  • 1
    One should probably point out that this is exactly equivalent to `system("rm -rf ~/.Trash/*")` in many other languages. – Charles Duffy Mar 20 '17 at 21:25
  • I like some of the files in my trash. I'm glad I didn't just run it and delete them all. – Pro Q Mar 21 '17 at 03:41
1

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.

Pro Q
  • 4,391
  • 4
  • 43
  • 92