Skip to content

Instantly share code, notes, and snippets.

@morganestes
Created August 28, 2020 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save morganestes/088a062c5bbce445457ff88ceea355eb to your computer and use it in GitHub Desktop.
Save morganestes/088a062c5bbce445457ff88ceea355eb to your computer and use it in GitHub Desktop.
bash script to create a new shell script or library
#!/bin/bash
# Creates a new shell script or library
#
# Libraries should have a .sh file extension and ARE NOT executable.
# Commands should have no file extension and ARE executable by default.
function new_shell_script() {
local file="${1:-"my_new_script"}"
local filename
local extension
local script
# create the file
if [[ ! -r "${file}" ]]; then
touch "${file}"
fi
# prepend the opening hashbang and main function to the file
# keep the text flush left here so it's not indented weirdly in the output
script="
#!/bin/bash
#
# What this script does
function main() {
echo 🆕 ${file} created!
}
main
"
echo "${script}$(cat "${file}")" > tmpfile && mv tmpfile "${file}"
# files with an ".sh" extension are assumed to be non-executable libraries
filename=$(basename "${file}")
extension="${filename##*.}"
if [[ "sh" != "${extension}" ]]; then
chmod +x "${file}"
fi
# make sure it works now
if [[ -x "${file}" ]]; then
./"${file}"
else
sh "${file}"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment