Generating a template for shell script
Idea
Prompt the user to provide a filename
Create a file with provided name in a specific path
The file will consist of :
Purpose
Version
Created Date (should use the current date of creation)
Modified Date
Author (should use the username of the person who created the file)
Start of the script
End of the script
Make the file executable
Example code
#!/bin/bash
echo -e "Please provide filename you want to create: \c"
read -r file
path=/home/nax/devops/shell-scripts
touch $path/$file.sh
echo '#!/bin/bash' > $path/$file.sh
echo '#Purpose:' >> $path/$file.sh
echo '#Version:' >> $path/$file.sh
echo '#Created Date:' $(date) >> $path/$file.sh
echo '#Modified Date:' >> $path/$file.sh
echo "#Author: $(whoami)" >> $path/$file.sh
echo '#START' >> $path/$file.sh
echo '#END' >> $path/$file.sh
chmod 777 $path/$file.sh
This script will create a file with the extension “.sh” and appending the required information to the file.
After creating the template script
Make this script as a command so that i can use it anywhere in the terminal:
- Change the permission to executable by everyone using :
chmod 777 template
Things I learned and mistakes I made from these simple project
read -r file
- -r will treated as literal characters.
Command substitution
Command substitution allows you to capture the output of a command and use it as part of another command or assign it to a variable.
2 ways to use command substitution ( both will work ) :
- Old way using `` (backticks)
echo "Today's date is `date`"
> Today's date is Wed Feb 26 10:19:43 PM +08 2025
- Modern way using $()
echo "Today's date is $(date)"
> Today's date is Wed Feb 26 10:19:54 PM +08 2025
Note: quotation plays a important role when we use command substitution
Single quotes vs Double quotes
single quotes prevent variable expansion and command substitution. This means that anything inside single quotes is treated as a literal string
Double quotes allow variable expansion and command substitution.
echo "#Author: $(whoami)"
> #Author: nax
echo '#Author: $(whoami)'
> #Author: $(whoami)