简体   繁体   中英

Bash equivalent for PowerShell's Write-Host (write to terminal but don't pipe to stdout)

In PowerShell I can do this:

function Get-Foo()
{
   Write-Host "Calculating result..."
   return 42
}

$x = Get-Foo
Write-Host "The answer is $x" # output: The answer is 42

So Calculating result.. is output to the console, but it's not present in the pipeline so I can just take the method's "return value" and it works

However in bash I don't have Write-Host and something like this won't work:

function getfoo {
   echo "Calculating result..."
   echo "42"
}

x=$(getfoo)
echo $x # output will include "Calculating result..."

I realize I can save to a file and print after, just wondering if there's a more elegant alternative

Redirect your output to /dev/tty to print directly to the terminal:

echo "Calculating result..." > /dev/tty

Simple example:

# Only '42' is stored in $output
$ output=$(echo "Calculating result..." > /dev/tty; echo 42)
Calculating result...

Another, probably better option - if you want to give the caller the option to still capture - or silence - the status information - is to redirect to stderr , with >&2 :

# Only '42' is stored in $output
$ output=$(echo "Calculating result..." >&2; echo 42)
Calculating result...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM