Sunday, 10 September 2017

Get result of two or more commands in the same line and redirect the result to a file

Forgive me for the long title of the post but titles should be descriptive of the content that follows and I just wanted to make sure of it for this article.

Generally when we chain commands by using semicolons, the output of each distinct command follows on a new line as shown below:

[root@pbox ~]# uname -a;date
Linux pbox 3.10.0-514.el7.x86_64 #1 SMP Tue Nov 22 16:42:41 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
Sun Sep 10 13:46:26 IST 2017


But what if we have a scenario in which we require the resulting output of the commands we execute to be on the same line. A scenario where I've had this requirement was to interpolate multiple variable names into a csv file. A quick and easy way would be:

[root@pbox ~]# echo "$UID, $PWD" > text.csv
[root@pbox ~]# cat text.csv
0, /root
[root@pbox ~]#


For some odd reason which I can't recall this simple redirect wasn't working for me so I had to come up with something fancier.

I decided to use a subshell, enclose the commands within that subshell and redirect them to the required file. Here's an example:

[root@pbox ~]# ( echo -n "Logged into `hostname`"; echo ", on `date`" ) > text
[root@pbox ~]# cat text
Logged into pbox, on Sun Sep 10 13:57:47 IST 2017
[root@pbox ~]#

The -n flag with the echo removes the new line it add at the end of it's output.

We could do something similar without invoking a subshell and that is by using curly braces {}.
Here's an example:

[root@pbox ~]# { echo -n "This is a `uname -s` box "; echo ", btw Today is `date`" ;} > text
[root@pbox ~]# cat text
This is a Linux box , btw Today is Sun Sep 10 14:01:37 IST 2017
[root@pbox ~]#

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...