How to cross a Horse and a Tremulous Doe

“To beat (Bash) or not to beat,” one Danish prince asked. So I had a similar question when we got a Bamboo build server in our company. How can a Bamboo job executing a Bash or Cmd script write commands that both the Windows command line interpreter and the Linux wrapper can understand?

At our company, the cross-platform Python language is used as the scripting language for Bamboo plans. But to run scripts on Windows and Linux, different code is used, something like the following:

Windows:

call %PYTHON_ENV%Scriptsactivate.bat
python имя_скрипта.py %bamboo_issue_key%

linux:

source ~/.bash_profile
source $PYTHON_ENV/bin/activate
python имя_скрипта.py $bamboo_issue_key

Commands understood by Linux will fail on Windows and vice versa. What to do in this situation? Run jobs only for agents with a specific operating system – rejecting half of available agents? I printed out a comparison list of all Bash and Windows command; tried to find the answer on the Internet; asked questions on specialized sites. Finally on stackoverflow I found an elegant solution.

In Windows Cmd, a line that starts with a “:” indicates the start of a label. If the label name is missing or does not contain the correct name from the point of view of the shell, then this line is ignored! What about in Linux? The colon character “:” is equivalent to true in most POSIX shells. Historically, Bush does not have built-in true and false commands. Instead, true was just an alias “:” and false was something like let 0.

There is no goto command in Linux. But with the heredocs syntax, one or more sections of code can be skipped:

echo "Run this"
cat >/dev/null <<GOTO_1
echo "Don't run this"
GOTO_1
echo "Also run this"

Adding all the knowledge above, we get the following code:

:<<"::CMDLITERAL"
@ECHO OFF
GOTO :CMDSCRIPT
::CMDLITERAL

source ~/.bash_profile
source $PYTHON_ENV/bin/activate
python -c "import platform; print(f"{platform.system()}")"
exit $?

:CMDSCRIPT
call %PYTHON_ENV%Scriptsactivate.bat
python -c "import platform; print(f"{platform.system()}")"

A beautiful solution that allows you to run a Bamboo plan on any agent (Linux or Windows) with a Python interpreter installed.

The only thing I haven’t explained is what are those strange $ symbols? coming after the exit command.

In Bush, the $? must come before the next line with a colon “:” because “:” escapes $? to 0 (false).

Other solutions were suggested in the stackoverflow discussion, but it seemed to me that the solution outlined in the article is more concise and visually separates Bush and Cmd code.

Don’t believe when they tell you it can’t be done. A little more effort – and as a result you can run cross-platform scripts that run on both Linux and Windows.

Similar Posts

Leave a Reply Cancel reply