Put Command Output into String

How do I set a variable to the output of a command in Bash?

In addition to backticks `command`, command substitution can be done with $(command) or "$(command)", which I find easier to read, and allows for nesting.

OUTPUT=$(ls -1)
echo "${OUTPUT}"

MULTILINE=$(ls \
-1)
echo "${MULTILINE}"

Quoting (") does matter to preserve multi-line variable values; it is optional on the right-hand side of an assignment, as word splitting is not performed, so OUTPUT=$(ls -1) would work fine.

Bash compare a command output to string

Better do this, =~ for bash regex :

#!/bin/bash

var="$(git status -uno)"

if [[ $var =~ "nothing to commit" ]]; then
echo "Up-to-date"
else
echo "need to pull"
fi

or

#!/bin/bash

var="$(git status -uno)"

if [[ $var == *nothing\ to\ commit* ]]; then
echo "Up-to-date"
else
echo "need to pull"
fi

Convert an output to string

How to fix the problem

The shell (or the test command) uses = for string equality and -eq for numeric equality. Some versions of the shell support == as a synonym for = (but = is defined by the POSIX test command). By contrast, Perl uses == for numeric equality and eq for string equality.

You also need to use one of the test commands:

if [ "$a" = "AC adapter : online" ]
then echo "ONLINE"
else echo "OFFLINE"
fi

Or:

if [[ "$a" = "AC adapter : online" ]]
then echo "ONLINE"
else echo "OFFLINE"
fi

With the [[ operator, you could drop the quotes around "$a".

Why you got the error message

When you wrote:

if $a -eq "AC adapter : online"

the shell expanded it to:

if AC adapter : online -eq "AC adapter : online"

which is a request to execute the command AC with the 5 arguments shown, and compare the exit status of the command with 0 (considering 0 — success — as true and anything non-zero as false). Clearly, you don't have a command called AC on your system (which is not very surprising).

This means you can write:

if grep -q -e 'some.complex*pattern' $files
then echo The pattern was found in some of the files
else echo The pattern was not found in any of the files
fi

If you want to test strings, you have to use the test command or the [[ ... ]] operator. The test command is the same as the [ command except that when the command name is [, the last argument must be ].

Capturing command output in Powershell as string instead of array of strings

Just wrap the "inner" command in parentheses, and use the -join operator with "`n" on the right.

# Preserve line breaks
$result = (ipconfig) -join "`n";

# Remove line breaks
$result = (ipconfig) -join '';

Get Command Prompt Output to String In Java

First you need a non-blocking way to read from Standard.out and Standard.err

private class ProcessResultReader extends Thread
{
final InputStream is;
final String type;
final StringBuilder sb;

ProcessResultReader(@Nonnull final InputStream is, @Nonnull String type)
{
this.is = is;
this.type = type;
this.sb = new StringBuilder();
}

public void run()
{
try
{
final InputStreamReader isr = new InputStreamReader(is);
final BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
{
this.sb.append(line).append("\n");
}
}
catch (final IOException ioe)
{
System.err.println(ioe.getMessage());
throw new RuntimeException(ioe);
}
}

@Override
public String toString()
{
return this.sb.toString();
}
}

Then you need to tie this class into the respective InputStream and OutputStreamobjects.

    try
{
final Process p = Runtime.getRuntime().exec(String.format("cmd /c %s", query));
final ProcessResultReader stderr = new ProcessResultReader(p.getErrorStream(), "STDERR");
final ProcessResultReader stdout = new ProcessResultReader(p.getInputStream(), "STDOUT");
stderr.start();
stdout.start();
final int exitValue = p.waitFor();
if (exitValue == 0)
{
System.out.print(stdout.toString());
}
else
{
System.err.print(stderr.toString());
}
}
catch (final IOException e)
{
throw new RuntimeException(e);
}
catch (final InterruptedException e)
{
throw new RuntimeException(e);
}

This is pretty much the boiler plate I use when I need to Runtime.exec() anything in Java.

A more advanced way would be to use FutureTask and Callable or at least Runnable rather than directly extending Thread which isn't the best practice.

NOTE:

The @Nonnull annotations are in the JSR305 library. If you are using Maven, and you are using Maven aren't you, just add this dependency to your pom.xml.

<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>1.3.9</version>
</dependency>

How to concatenate stdin and a string?

A bit hacky, but this might be the shortest way to do what you asked in the question (use a pipe to accept stdout from echo "input" as stdin to another process / command:

echo "input" | awk '{print $1"string"}'

Output:

inputstring

What task are you exactly trying to accomplish? More context can get you more direction on a better solution.

Update - responding to comment:

@NoamRoss

The more idiomatic way of doing what you want is then:

echo 'http://dx.doi.org/'"$(pbpaste)"

The $(...) syntax is called command substitution. In short, it executes the commands enclosed in a new subshell, and substitutes the its stdout output to where the $(...) was invoked in the parent shell. So you would get, in effect:

echo 'http://dx.doi.org/'"rsif.2012.0125"

How to concatenate multiple lines of output to one line?

Use tr '\n' ' ' to translate all newline characters to spaces:

$ grep pattern file | tr '\n' ' '

Note: grep reads files, cat concatenates files. Don't cat file | grep!

Edit:

tr can only handle single character translations. You could use awk to change the output record separator like:

$ grep pattern file | awk '{print}' ORS='" '

This would transform:

one
two
three

to:

one" two" three" 


Related Topics



Leave a reply



Submit