A Bash script for quickly creating Bash scripts
Have you ever thought about the process you have to go through to create a bash script? Create file, make the file executable, open file, add the shebang on the first line, go to the second line, start writing the script. Sounds like a ton of work that can be automated. When I realized this, I quickly got to work to create a bash script that would automate this. I wanted a script that would allow me to type newbash my-script.sh
to create and open a new bash script in a text editor.
Here it is:
#!/bin/bash # Create a boilerplate bash script and open it in vim. # Usage: newbash <file-to-create> if [ -z "$1" ]; then echo 'No file name provided.' exit 1 elif [ -e "$1" ]; then echo 'File already exists.' exit 1 fi # Create the file. # Make the file executable. # Add a shebang and a newline to the file. touch "$1" \ && chmod u+x "$1" \ && echo '#!/bin/bash' > "$1" \ && echo '' >> "$1" \ && vi +2 "$1" # Open file and position cursor on the second line.
If you don't use vim, just change the last line to make the file open in whichever text editor you use.
I placed the script in the ~/bin/
directory, so now every time I need to create a bash script, I no longer have to go through tedious boilerplate steps. Now, all that I need to do is a simple newbash my-script.sh
. Hope this saves you time.