Comments in a multi-line bash command

23,334

Solution 1

Put the pipes at the end of line with the comments after it:

$ echo 'foo' |
sed 's/f/a/' | # change first f to a
sed 's/o/b/' | # change first o to b
sed 's/o/c/'   # change second o to c
abc

Solution 2

If you happen upon this question while looking to comment a non-pipeline multiline command:

$ echo 'foo' |
sed -e 's/f/a/' `: # change first f to a` \
    -e 's/o/b/' `: # change first o to b` \
    -e 's/o/c/' `: # change second o to c`

Unless you're doing something really perverse like automating commenting, I can't see a reason to prefer this over Mikel's answer for a pipe, but if you really wanted to:

$ echo 'foo' |
sed 's/f/a/' | `: # change first f to a` \
sed 's/o/b/' | `: # change first o to b` \
sed 's/o/c/'   `: # change second o to c`

or:

$ echo 'foo' |
sed 's/f/a/' `: # change first f to a` |
sed 's/o/b/' `: # change first o to b` |
sed 's/o/c/' `: # change second o to c`

Source: http://unix.derkeiler.com/Newsgroups/comp.unix.solaris/2005-07/0991.html

Solution 3

Well, I prefer this way,

echo 'foo' | {
  # change first f to a
  # you can add more lines of comment on the command options
  sed 's/f/a/'
} | {
  # change first o to b
  sed 's/o/b/'
} | {
  # change second o to c
  sed 's/o/c/' 
}
Share:
23,334

Related videos on Youtube

Nicolas Raoul
Author by

Nicolas Raoul

I am Nicolas Raoul, IT consultant in Tokyo. Feel free to copy/paste the source code from my StackExchange answers, I release it to the public domain.

Updated on September 17, 2022

Comments

  • Nicolas Raoul
    Nicolas Raoul over 1 year

    This single-command BASH script file is difficult to understand, so I want to write a comment for each of the actions:

    echo 'foo'     \
    | sed 's/d/a/' \
    | sed 's/e/b/' \
    | sed 's/f/c/' \
    > myfile
    

    (sed is just an example, actually it is a mix of greps and trs and awks)

    I would hate having to duplicate lines, or having each comment far away from the line it applies to.
    But at the same time BASH does not seem to allow "in-line" comments.

    Any elegant way to solve this problem?

  • MrCholo
    MrCholo almost 5 years
    makes sense, since something is expected to follow the pipe