Created
August 28, 2020 00:16
-
-
Save morganestes/088a062c5bbce445457ff88ceea355eb to your computer and use it in GitHub Desktop.
bash script to create a new shell script or library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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