Here’s another little Bash function. It makes it possible to create a new script in one command, creating the file with shebang, making it executable, and opening it in your editor.
Just run newscript scriptname.rb to create a new ruby script with a /usr/bin/env ruby shebang. It also recognizes Python, Perl, and bash extensions, add more as needed.
You can also create a directory with “skeleton” scripts. If you have a list of includes that you always use in your shell scripts, add a ext.txt file to that directory (e.g. rb.txt or py.txt). By default that directory is ~/.newscript_defaults, but you can modify it in the config section. As an example, you might have a sh.txt file that sources a file of common functions you use in bash scripts, or an rb.txt file that includes contains # encoding: utf-8 to be appended after the shebang.
Just add this to ~/.bash_profile, or wherever you source your shell functions from. You’ll need to edit your script location in the scriptdir variable at the top.
# Touch, make executable and start editing a new script# $ newscript my_new_script.sh# edit default shebangs within the function# include additional skeleton files as [extension].txt# in the $defaults_txt folder defined in confignewscript(){# Config# where your scripts are storedlocalscriptdir=~/scripts/
# if no extension is provided, default tolocaldefault_ext=rb
# optional, where skeleton scripts (e.g. rb.txt) are storedlocaldefaults_txt=~/.newscript_defaults/
# End configlocalfilename="${scriptdir%/}/$1"if[[$#==0]];then# no argument, display help and exitecho-e"newscript: touch, make executable and \start editing a new script.\n\033[31;1mError:\033[37;1m Missing filename\033[0m\n\n\Usage: mynewscript SCRIPT_NAME.ext\n"return1fi# get the extension from the filenameext=${filename#*.}# if there's no extenstion, add defaultif[[$ext==$filename]];thenext=$default_extfilename=$filename.$extfi# if no script with this name already existsif[!-f$filename];then# create a file for the given extension with appropriate shebangcase$extinrb)echo-e"#!/usr/bin/env ruby">>$filename;;py)echo-e"#!/usr/bin/env python">>$filename;;pl)echo-e"#!/usr/bin/env perl">>$filename;;sh|bash)echo-e"#!/bin/bash">>$filename;;zsh|bash)echo-e"#!/bin/zbash">>$filename;;*)touch$filename;;# any other extension create blank fileesac# if skeleton files directory and a txt for the given extension existif[[-d${defaults_txt%/}&&-f${defaults_txt%/}/$ext.txt]];then# concatenate it to the filecat${defaults_txt%/}/$ext.txt>>$filenamefi# Add trailing newline to the new scriptecho-ne"\n">>$filename# Make it executablechmoda+x"$filename"echo-e"\033[32;1m$filename\033[0m"else# Specified filename already existsecho-e"\033[31;1mFile exists: $filename\033[0m"fi# Edit the script$EDITOR"$filename"}