Swift: Command line exit codes

Victor Jalencas asks, “So how do you return an exit code from a swift CLI program? i.e., what’s the equivalent of main?” Just use exit(). The following example sees if there’s at least one optional argument. If so, it exits with a status of 0 vs 1.

import Foundation
let test = (C_ARGC > 1)
exit(test ? 0 : 1)

You can test this from any command line script. I used this one:

#! /bin/csh
/Users/ericasadun/test
if ($? == 1) then
    echo "1"
else
    echo "0"
endif
/Users/ericasadun/test foo
if ($? == 1) then
    echo "1"
else
    echo "0"
endif

3 Comments

  • You could also just test using “echo $?” rather than doing the if … else… endif dance

  • You can use `import Darwin` instead of `import Foundation` here.

  • Thanks for the example, Erica