I'm looking for ways to enhance the clarity of my code comments. Specifically, I want the first comment to provide an overview of a code block, and the second comment—referring to the line starting with `tracked=`—to be more focused on that line. The issue is, the second comment tends to be too lengthy to fit on the same line as the code itself. Here's my current setup:
```bash
# skip parsing to print full line when a line doesn't start with
# trim leading whitespaces. Ref:
# https://web.archive.org/web/20121022051228/http://codesnippets.joyent.com/posts/show/1816
tracked="${tracked#"${tracked%%[![:space:]]*}"}"
if [[ "$tracked" =~ ^[^[:alnum:]] ]]; then
echo "$tracked"
continue
fi
```
Additionally, I wonder if it's logical to have comments that describe multiple blocks of code. Are there better practices for determining where comments should begin and end? Should I be using end marker comments, or could that be considered excessive?
5 Answers
For trimming whitespace, instead of your current approach, try this simpler method:
```bash
declare STRING=" tThis string has leading space."
shopt -s extglob
echo "${STRING##*([[:space:]])}"
```
This method uses extended globbing effectively to clear out leading spaces and makes your code cleaner.
For clear comments, consider using a structured approach similar to Doxygen. You can create blocks that describe each function and significant variables, like this:
```bash
##
# @name trim_leading_whitespace
# @brief Removes leading whitespace from the given variable.
# @param[in,out] variable Variable to modify.
##
trim_leading_whitespace() { ... }
```
This makes comments easier to read and gives context to anyone working with your code. I generally use this method for clarity in my scripts.
Remember, your code is the best documentation. It should be straightforward and easy to read rather than trying to be clever. If there’s any conflict between your code and comments, both might need revision!
A good comment is one that improves understanding. Ask yourself, will someone unfamiliar with the code grasp its purpose in three months? I recommend visually separating comments from code by using something like `#--` followed by a space, making them more noticeable, especially in environments where syntax highlighting isn’t available.
Here's a clearer way to structure your comments for a snippet:
```bash
# Skip parsing if the line doesn’t start with a non-whitespace character.
# Trim leading whitespaces from 'tracked'. Reference:
# https://web.archive.org/web/20121022051228/http://codesnippets.joyent.com/posts/show/1816
tracked="${tracked#"${tracked%%[![:space:]]*}"}"
if [[ "$tracked" =~ ^[^[:alnum:]] ]]; then
echo "$tracked"
continue
fi
```
This format distinguishes the overview from specific code comments, enhancing legibility and context.
The `$()` isn't needed there; you can directly declare the string like this instead: `declare STRING=$' tThis string has leading whitespace.'`