There are several ways to execute various commands on bash and cmd with the same script.
cmd will ignore lines starting with :; as mentioned in other answers. It also ignores the next line if the current line ends with the rem ^ command, since the ^ character will exit the line break and the next line will be considered as a rem comment.
Regarding bash ignoring cmd lines, there are several ways. I have listed some ways to do this without breaking cmd commands:
Optional command # (not recommended)
If cmd does not have the # command when the script is executed, we can do this:
The # character at the beginning of the cmd line makes bash treat this line as a comment.
The # character at the end of the bash line is used to comment on the \r character, as Brian Thompsett pointed out in his answer . Without this, bash will throw an error if the file has \r\n line endings required by cmd .
By executing # 2>nul , we trick cmd to ignore the error of some non-existent # command, but at the same time execute the following command.
Do not use this solution if PATH has a # command or if you do not have control over the commands available for cmd .
Using echo to ignore the # character on cmd
We can use echo with its output redirected to insert cmd commands into the bash scope:
echo >/dev/null
Since the # character has no special meaning in cmd , it is considered as part of the echo text. All we had to do was redirect the output of the echo command and insert other commands after it.
Empty #.bat file
echo >/dev/null
The line echo >/dev/null # 1>nul 2> #.bat creates an empty #.bat file during cmd (or replaces the existing #.bat , if any) and does nothing during bash .
This file will be used by the next line of cmd , even if there is another # command in PATH .
The del #.bat command in cmd specific code deletes the file that was created. You only need to do this in the last line of cmd .
Do not use this solution if the #.bat file may be in your current working directory, as this file will be deleted.
Recommended: use a document here to ignore cmd commands in bash
:; echo 'Hello bash!';<<: echo Hello cmd! & ^ :
By placing the ^ character at the end of the cmd line, we elude line breaks and using : as the separator here in the document, the contents of the separator line will not affect cmd . Thus, cmd will execute its line only after the end of the line : having the same behavior as bash .
If you want to have several lines on both platforms and execute them only at the end of the block, you can do this:
:;(
As long as there is no cmd line with exactly here-document delimiter , this solution should work. You can change the here-document delimiter to any other text.
In all presented solutions, the commands will be executed only after the last line , making their behavior consistent if they do the same on both platforms.
These solutions should be saved in files with \r\n as line breaks, otherwise they will not work on cmd .