Skip to main content

Lifecycle hooks

$pre and $post

To set lifecycle hooks for a script, use the $pre and $post directives within the scripts object. These directives define actions that should run before and after a specific script executes, respectively.

  • $pre (scriptName): Runs before the specified script.
  • $post (scriptName): Runs after the specified script.
  • The script name is enclosed in parentheses, linking the directive to the target script.
  • The command or operation follows the directive as a string or a function.
export default {
scripts: {
"$pre (yourScript)": "echo 'Preparing for ...'",
"yourScript": "someCommand",
"$post (yourScript)": "echo 'Done!'"
}
}

$catch

To handle errors for a script, use the $catch directive within the scripts object. This allows you to define specific actions to take when a script encounters an error.

  • $catch (scriptName): Specifies the error-handling action for the given script.
  • The script name appears within parentheses, linking the directive to the target script.
  • The error response command or operation follows the directive as a string or a function.
export default {
scripts: {
"runTask": "someTasks",
"$catch (runTask)": "echo 'An error occurred during execution!'"
}
}

This ensures that any errors encountered during script execution trigger a predefined response.

Chaining

$catch is particularly useful because, when chaining commands, it ensures that the process continues even if one element fails, if that behavior is desired.

Check the following example:

export default {
scripts: {
"yourScript1": "echo someText1",
"yourScript2": "exit 10",
"yourScript3": "echo someText3",
"chain": "jko -l=w yourScript1 && jko -l=w yourScript2 && jko -l=w yourScript3",
}
}

yourScript2 will intentionally fail (for demonstration purposes), breaking the chain:

$ jko chain someText1

jko end - yourScript2: "exit 10" Failed.

jko end - chain: "jko -l=w yourScript1 && jko -l=w yourScript2 && jko -l=w yourScript3" Failed.

Now, let's add $catch:

export default {
scripts: {
"yourScript1": "echo someText1",
"yourScript2": "exit 10",
"$catch (yourScript2)": "echo Ok!",
"yourScript3": "echo someText3",
"chain": "jko -l=w yourScript1 && jko -l=w yourScript2 && jko -l=w yourScript3",
}
}

$ jko chain someText1 Ok!

jko warn - $catch (yourScript2) executed.

someText3

jko end - Successful execution of chain.

Was this content valuable?