How to Add Comments to Your Scripts 📜

If you write scripts and want to add comments between the command arguments, you might find this post useful! 😉

2 min read
How to Add Comments to Your Scripts 📜
Photo by Min An from Pexels

At work, I write a lot of scripts to automate commands, like Dockerfile, GitLab CI, or just a group of commands for a specific task. In my scripts, I like to add a lot of comments to indicate what the command does or why. Sometimes I even add comments between its arguments, as some of them may not be clear. 🥴

These comments may be obvious for experienced developers, but I think they can help readers, as they might not have the same knowledge. It might even be myself in a few months or years, as I regularly switch from one language to another, depending on the project I am working on.

Unfortunately, the comments between the arguments of a multiline command differ from shell to shell. So sometimes, I find myself looking for an example in a previous project to comment on the commands of the script I am writing. 🔎

To facilitate the development of my future scripts, I decided to write this little post as my personal memo. 📝

I hope this helps you write better scripts as well! Enjoy! 😊

Bash

  • Normal comments: # Comment
  • Comments between arguments: `# Comment`
# Downloads the package lists from the repositories and updates them
apt-get update \
# Install the following dependencies with the specified versions
# To check if the versions are up to date: https://packages.debian.org/search?suite=buster&keywords=wget
&& apt-get install --no-install-recommends --no-install-suggests -y \
  locales=2.28-10                 `# To be able to change the language` \
  unzip=6.0-23+deb10u2            `# To be able to unzip the source files` \
  wget=1.20.1-1.1                 `# To be able to obtain the source files`

Example of a multiline command in Bash with comments

PowerShell

This excerpt is taken from my Lint PowerShell scripts with PSScriptAnalyzer post.

  • Normal comments: # Comment
  • Comments between arguments: <# Comment #>
# Sets values for a registered module repository
Set-PSRepository \
  -ErrorAction Stop           <# Action to take if a command fails #> \
  -InstallationPolicy Trusted <# Installation policy (Trusted, Untrusted) #> \
  -Name PSGallery             <# Name of the repository #> \
  -Verbose;                   <# Write verbose output #>

Example of a multiline command in PowerShell with comments