Questions about the use of line continuation (\) together with inline comments (# comment) in shell scripts is a somewhat frequent topic on Unix and Linux forums. Unfortunately, there is no simple elegant solutions available for any of the standard shells such as bash, ksh93, zsh or the POSIX shell.
Consider the following simple shell script:
#!/bin/ksh93 find ./ \ -type f \ -name "*.pyc"
Suppose you want to add comments describing each argument to the find utility. You might (I did the first time I came across this issue!) naively expect the following to work:
#!/bin/ksh93 find ./ \ # look for regular files \ -type f \ # look for filenames with .pyc extension \ -name "*.pyc"
You will quickly find that the above script errors out due to the fact that anything after “#” is ignored, including the line continuation slash. It is not a ksh93 issue; bash and zsh also fail.
There are a number of workarounds for this issue – the two most common are subshells and arrays. The following example demonstrates the subshell approach using backticks (`):
#!/bin/ksh93 find ./ \ `# look for regular files` \ -type f \ `# look for filenames with .pyc extension``\ \ -name "*.pyc"
Does PowerShell on Linux (pwsh) require similar workarounds? The answer is no.
PowerShell uses different syntax for multiline or embedded comments. Embedded or multiline comments use the <# comment #> syntax. Line continuation uses the backtick (`) character.
The following examples demonstrate how you can use line continuation and inline comments with PowerShell (pwsh) on Linux:
$ pwsh -i PowerShell 7.1.0 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /home/fpm/tmp> Get-Process -Name atd NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 0 0.00 2.77 0.11 1102 …02 atd PS /home/fpm/tmp> Get-Process <# comment #> -Name <# comment #> atd NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 0 0.00 2.77 0.11 1102 …02 atd PS /home/fpm/tmp> Get-Process <# comment #> ` >> <# comment #> ` >> -Name ` >> <# comment #> ` >> atd NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 0 0.00 2.77 0.11 1102 …02 atd PS /home/fpm/tmp> exit $
As you can see, unlike Unix and Linux shells such as bash or ksh93, pwsh handles embedded comments in multiline commands and scripts in an elegant and consistent manner. +1 for PowerShell!