Bash: adding inline comments within long/multiline command

This is a wiki page. Be bold and improve it!

If you have any questions about the content on this page, don't hesitate to open a new ticket and we'll do our best to assist you.

One can break long commands like this:

cat "$1" | tr '\n' '\t' | sed  's/\t\t/\n/g' | sed 's/[0-9]*\t//1' | sed 's/^[^\t]*\t//' | sed 's/\t-/\n-/' | sed 's/\t/ /g' | sed 's/  / /g' | sed 's/^-//' | sed 's/^ *//' | sed 's/<[ib]>//' |  sed 's/<\/[ib]>//'

into multiple lines, using the backslash at the last character of each line:

cat "$1" \
| tr '\n' '\t' \
| sed  's/\t\t/\n/g'\
| sed 's/[0-9]*\t//1'\
| sed 's/^[^\t]*\t//'\
| sed 's/\t-/\n-/'\
| sed 's/\t/ /g'\
| sed 's/  / /g'\
| sed 's/^-//'\
| sed 's/^ *//'\
| sed 's/<[ib]>//'\
|  sed 's/<\/[ib]>//'

However, Bash does not allow to insert line comments:

cat "$1" \
# Comment 1: this will break the script.
| tr '\n' '\t' \
# Comment 2: idem.
| sed  's/\t\t/\n/g'\
| sed 's/[0-9]*\t//1'\
| sed 's/^[^\t]*\t//'\
| sed 's/\t-/\n-/'\
| sed 's/\t/ /g'\
| sed 's/  / /g'\
| sed 's/^-//'\
| sed 's/^ *//'\
| sed 's/<[ib]>//'\
|  sed 's/<\/[ib]>//'

The solution is to use the backtick command substitution like this:

cat "$1" \
`# Comment 1: this is a "command" that does nothing and is ignored by bash.`

| tr '\n' '\t' \
`# Comment 2: idem`.
| sed  's/\t\t/\n/g'\
| sed 's/[0-9]*\t//1'\
| sed 's/^[^\t]*\t//'\
| sed 's/\t-/\n-/'\
| sed 's/\t/ /g'\
| sed 's/  / /g'\
| sed 's/^-//'\
| sed 's/^ *//'\
| sed 's/<[ib]>//'\
|  sed 's/<\/[ib]>//'