1

I'm running a program and writing its output into a variable like this;

var=$(/usr/bin/someProgram someCommand)

And this is the output of the command;

$ /usr/bin/someProgram someCommand
12345

So in this case my var equals 12345.

However, sometimes its output can be like this;

$ /usr/bin/someProgram someCommand
test
12345

which as you can see includes the word test before the result I need. In this case my first code gets broken because now my var equals:

test 
12345

I need to remove the word test from the result so my var can be 12345 again. I tried the following code but it didn't work as I expected;

var=$(/usr/bin/someProgram someCommand)
var=$(printf '%s\n' "${var//test/}")

Because now if I run a command like this;

$ /usr/bin/someProgram someCommand $var

It doesn't work because it's trying to run the above command like this;

$ /usr/bin/someProgram someCommand     <-- # notice there is a space here and 12345 is given below but it is supposed to be given right after someCommand
12345

-x output shows there's actually a space before the 12345 after removing the string test from it;

+ var='
12345'

another -x output for the latter example;

++ '/usr/bin/someProgram someCommand
12345'

I don't know how this space is happening but I guess I need to remove it for this to work and I don't know how.

Marry Jane
  • 305
  • 2
  • 15
  • What about `var=$(/usr/bin/someProgram someCommand | grep -v test)`? – majusebetter Jul 15 '22 at 16:20
  • Honestly, that just works for me. Thanks :D – Marry Jane Jul 15 '22 at 17:20
  • Your example is wrong, there is no newline because you are not quoting the value. See also [When to wrap quotes around a shell variable?](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Jul 16 '22 at 08:38

2 Answers2

2

You can use bash string substitution to anything followed by \n:

var="$(/usr/bin/someProgram someCommand)"
echo "${var##*$'\n'}"

12345
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

If you know that the REAL output is always in the last line:

var="$(/usr/bin/someProgram someCommand | tail -1)"

With the advantage that it will remove any leading lines.

dash-o
  • 13,723
  • 1
  • 10
  • 37