23

When invoking long, switch-heavy commands, it's a good practice to write them in shell scripts. Is there an easy way to comment lines in such scripts? I've tried the following methods, but neither works.

# the \ is also commented out, resulting in "command" and "--good-switch".
command \
  #--bad-switch \
  --good-switch \

# seems to send an extra argument to the command
command \
  \ #--bad-switch \
  --good-switch
1
  • 1
    The second one causes a space to be sent as an argument (\ escapes the next character, which "hides" newlines but makes spaces significant). – geekosaur Mar 21 '11 at 15:27
16

This might be an option: store the command and args in an array, then execute it after

# build the command
cmd=( ls
        -F
      # -a   # comment out this option temporarily
        -l
    )
# $cmd is now an array with 3 elements

# execute it
"${cmd[@]}"
1
  • This is bash-only… – Socob Sep 28 '16 at 8:11
4

I always moved the commented ones just after the command.

command \
  --good-switch
# --bad-switch          with explanation here, if needed
2

See the answer by Digital Ross.

See also the question I just posted, bash multi line command with comments after the continuation character.

This would be a useful feature. It is a pity it does not have standard support.

1

The issue is that the slashes are removed before the line is parsed, so the first command is parsed as if you'd written command #--bad-switch --good-switch. If you have a really long sequence of commands, you could for example write a line-by-line comment block above or below it, explaining each in turn, or you could store the parameters in a variable (although that often gives quoting headaches with special characters).

1
  • 1
    That doesn't seem to be the case. --good-switch is interpreted as a command. – user4518 Mar 21 '11 at 15:47
1

a comment brakes the chain of conected lines, so the simplest solution would be to move the commented lines at the end of the list.

command \
  --good-switch \
  # --bad-switch \

If you don't want to change the order, you can use the : command (the colon utility, which does nothing) to keep the connected lines intact:

command \
  `: --bad-switch `\
  --good-switch \

I tested with this:

function command { 
  echo "num args:" $#;
}
0
$ echo abc `# comment` \
>      def `# comment 2` \
>      ghi
abc def ghi

$ echo abc `# comment` \
>      `#def # comment entire line` \
>      ghi
abc ghi

The backticks perform Command Substituion. This works because there is no standard output from executing a comment.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy