Skip to content

Instantly share code, notes, and snippets.

@fearthecowboy
Created April 29, 2022 20:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fearthecowboy/7b13ac93bf4162371237d2a611e5cee7 to your computer and use it in GitHub Desktop.
Save fearthecowboy/7b13ac93bf4162371237d2a611e5cee7 to your computer and use it in GitHub Desktop.
This one script can be saved as any of [.cmd, .bat, .ps1, .sh] and will run under cmd.exe, powershell, pwsh, bash and zsh.
#!/usr/bin/env -S bash # > NUL 2>&1 || echo off && goto init:
function shh() { return; } ; shh \\<<shh
## THIS IS THE START OF THE POWERSHELL SCRIPT #################################
write-host "Setting variable in powershell"
$env:abc=300
return;
## THIS IS THE END OF THE POWERSHELL SCRIPT ###################################
<#
shh
## THIS IS THE START OF THE POSIX SCRIPT ######################################
# check to see if we've been dot-sourced
sourced=0
if [ -n "$ZSH_EVAL_CONTEXT" ]; then
case $ZSH_EVAL_CONTEXT in *:file) sourced=1;; esac
elif [ -n "$BASH_VERSION" ]; then
(return 0 2>/dev/null) && sourced=1
else # All other shells: examine $0 for known shell binary filenames
# Detects `sh` and `dash`; add additional shell filenames as needed.
case ${0##*/} in sh|dash) sourced=1;; esac
fi
if [ $sourced -eq 0 ]; then
echo 'This script is expected to be dot-sourced'
echo ''
echo "You should instead run '. $(basename $0)'"
exit
fi
echo "Setting variable in posix"
abc=300
return
## THIS IS THE END OF THE POSIX SCRIPT ########################################
## THIS IS THE START OF THE CMD SCRIPT ########################################
:init
echo "Setting variable in CMD"
set abc=300
: THIS IS THE END OF THE CMD SCRIPT ###########################################
:#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment