Home > Net >  Equivalent of Powershell `Out-File` for Bash
Equivalent of Powershell `Out-File` for Bash

Time:02-04

echo "C:\tools\somepath\toabinary\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append

How can I achieve the results this Powershell commmand gives using Bash? Unfortunately I can barely find something on the net.

This is meant to be used in a Github action.

CodePudding user response:

Bash and POSIX-compatible shells in general have no explicit command for saving stdout data to a file; they have redirection operators > and >> (also supported analogously in PowerShell), which correspond to Out-File and Out-File -Append, respectively:

# Bash equivalent of your command.
echo "C:\tools\somepath\toabinary\bin" >> "$GITHUB_PATH"
  • The character encoding is implied by the LC_CTYPE setting, as reported by locale, and it is almost always UTF-8 on modern Unix-like platforms.

  • In POSIX-compatible shells - unlike in PowerShell - both shell-only and environment variables are referenced with the same notation, using symbol $ before the variable name. Therefore, environment variable GITHUB_PATH must be referenced as $GITHUB_PATH.

  • As tripleee points out - unlike in PowerShell - it is best to enclose variables in double quotes ("...") to ensure that their value is used as-is, without being subject to the so-called shell expansions, notably word splitting, where unquoted values with embedded spaces become multiple arguments.

Note a fundamental difference between POSIX-compatible shells and PowerShell with respect to the data flowing through pipelines (|) / getting redirected with > and >>:

  • In POSIX-compatible shells, these operators serve as raw byte conduits, and the data may or may not represent text.
  • In PowerShell, they are conduits for .NET objects, which in the case of external programs invariably means interpretation as lines of text, as of PowerShell 7.3.2 - see this answer for background information.
  • Related