Search code examples
bashosx-lionlaunchd

Submitting a program to launchctl with arguments not working correctly


I found, that LaunchCtl skips arguments when using its 'submit' protocol.

I have the following script (script.sh):

#!/bin/bash
arg1="$1"
arg2="$2"
arg3="$3"
arg4="$4"
echo $arg1$arg2$arg3$arg4
exit 1

When I call script.sh from terminal, there's no problem with passing arguments into it. When I do the same thing through LaunchCtl, something goes wrong and the first argument disappears.

launchctl submit -l MyUniqueScript -p ROOT/script.sh -o ROOT/out.txt -e ROOT/err.txt "abc" "def" "ghi" "jkl"

I even check my process

launchctl list MyUniqueScript

I have all my arguments right there. Terminal prints them out.

{
"Label" = "MyUniqueScript";
"LimitLoadToSessionType" = "Background";
"OnDemand" = false;
"LastExitStatus" = 256;
"TimeOut" = 30;
"Program" = "/Users/ROOT/script.sh";
"StandardOutPath" = "/Users/ROOT/out.txt";
"StandardErrorPath" = "/Users/ROOT/err.txt";
"ProgramArguments" = (
    "abc";
    "def";
    "ghi";
    "jkl";
);
};

But what I have in out.txt is quite messed up:

defghijkl

Rather than

abcdefghijkl

Can anyone help me out with this? Does anyone know what I should do, or what Im mistaken?

I must also tell, that the above small example is, of course, not the original script I'm working on. This is just easier to show my problem with.

Please help me! Thanks!


Solution

  • Your launchctl syntax is wrong. The first "argument" should be the path to the script:

    launchctl submit -l MyUniqueScript -p ROOT/script.sh -o ROOT/out.txt -e ROOT/err.txt -- ROOT/script.sh "abc" "def" "ghi" "jkl"
    

    From the man page:

    submit -l label [-p executable] [-o path] [-e path] -- command [args]

    The -p setting appears to be for aliasing, though I'm not sure why that would be useful

    -p program
    What program to really execute, regardless of what follows the -- in the submit sub-command.

    So in your case, launchctl is treating your first argument as the script to be run, but really running your script because you specified it as the executable with -p. Specify the script as arg 0, as given above, or just drop the -p specification and include the path to the script immediately before its args.