Skip to content

Instantly share code, notes, and snippets.

@sleekweasel
Created September 23, 2025 13:52
Show Gist options
  • Save sleekweasel/3ad0e4f2ab41da6de5d2832bb3676716 to your computer and use it in GitHub Desktop.
Save sleekweasel/3ad0e4f2ab41da6de5d2832bb3676716 to your computer and use it in GitHub Desktop.
GitHub action - shell-with-post-hook. No NPM modules.
name: 'Shell with Post Hook'
description: 'Run shell script with guaranteed post hook'
inputs:
main:
description: 'Main script to run (aborts job if exit code>10)'
required: true
post:
description: 'Post script to run (if $MAIN_EXIT_CODE<11)'
required: true
shell:
description: 'Shell'
required: false
default: 'bash'
outputs:
main-exit:
description: 'Exit code from main script'
runs:
using: 'node20'
main: 'index.js'
post: 'index.js'
// index.js - ONE script for both main AND post
const { execSync } = require('child_process');
function shell(command) {
try {
execSync(command, { stdio: 'inherit' });
return 0;
} catch (error) {
return error.status || 1;
}
}
const bash = process.env.INPUT_SHELL || 'bash';
const actionId = process.env.GITHUB_ACTION || 'action';
console.log(`ActionId=${actionId}`);
const tempDir = process.env.GITHUB_TEMP || process.env.RUNNER_TEMP || '/tmp';
const scriptPrefix = `/${tempDir}/${actionId}-script-`;
const mainScriptFile = `${scriptPrefix}main.sh`;
const postScriptFile = `${scriptPrefix}post.sh`;
// Check which phase we're in: if there's a post file, run it.
const isPost = shell(`test -f ${postScriptFile}`) === 0;
if (isPost) {
console.log(`Running post script... ${postScriptFile}`);
shell(`${bash} ${postScriptFile}`);
shell(`rm -f ${postScriptFile}`);
console.log(`... post script run.`);
} else {
console.log(`Running main script... ${mainScriptFile}`);
shell(`cat > ${mainScriptFile} << 'EOF'
${process.env.INPUT_MAIN}
EOF`);
const exitCode = shell(`${bash} ${mainScriptFile}`);
shell(`rm -f ${mainScriptFile}`);
console.log(`... main script run, writing post-hook script.`);
shell(`cat > ${postScriptFile} << 'EOF'
export MAIN_EXIT_CODE=${exitCode}
${process.env.INPUT_POST}
EOF`);
shell(`echo "main-exit=${exitCode}" >> $GITHUB_OUTPUT`);
process.exit(exitCode >= 10 ? exitCode : 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment