Skip to main content

Command Palette

Search for a command to run...

Generating a template for shell script

Published
2 min read

Idea

  1. Prompt the user to provide a filename

  2. Create a file with provided name in a specific path

  3. The file will consist of :

    1. Purpose

    2. Version

    3. Created Date (should use the current date of creation)

    4. Modified Date

    5. Author (should use the username of the person who created the file)

    6. Start of the script

    7. End of the script

  4. 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

  1. 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 ) :

  1. Old way using `` (backticks)
echo "Today's date is `date`"
> Today's date is Wed Feb 26 10:19:43 PM +08 2025
  1. 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)