1

I am trying to do a command that gives multiple lines; eg ldapwhoami and Id like to make it in a bash script that prints only the last line instead of all the command lines. I tried the following

#/bin/bash
$(ldapwhoami | sed 1d2d3d)

but it doesn't seem to work, any help would be appreciated.

Hi There
  • 167
  • 1
  • 5
  • 12
  • You are looking for `tail -n1` – hek2mgl Jul 16 '18 at 12:25
  • `head` and `tail` will do such tasks https://ss64.com/bash/tail.html – Lanting Jul 16 '18 at 12:26
  • *"that prints only the last line"* -- [`tail`](https://www.gnu.org/software/coreutils/manual/html_node/tail-invocation.html) is the command you are looking form. – axiac Jul 16 '18 at 12:26
  • If *all* the content you want to be rid of is on stderr, maybe you should just be using `ldapwhoami 2>/dev/null`. – Charles Duffy Jul 16 '18 at 12:59
  • ...that said, ignoring your error logs (as opposed to filtering out specific content or telling the command not to generate it in the first place) is generally a bad idea. Some day your LDAP server will be down and the 3 lines of stderr will have different contents, but they'll still be blocked from view. – Charles Duffy Jul 16 '18 at 13:00
  • @CharlesDuffy thank you for your input! i will make sure to keep that in mind. btw, may i ask another quick question about LDAP here? – Hi There Jul 16 '18 at 13:25
  • If by "here" you mean "on the site", sure -- so long as it's more about programming/development/scripting than about LDAP administration (which would tend to be a better fit for ServerFault). – Charles Duffy Jul 16 '18 at 13:27
  • Ah, it is indeed about LDAP but I cant post a new question and Im a bit stuck in a hurry. But i understand, thank you for the guidance. – Hi There Jul 16 '18 at 13:35

1 Answers1

5

To print only the final line use tail:

ldapwhoami | tail -n 1

To delete the first three lines with sed, change your command to:

ldapwhoami | sed '1d;2d;3d;'

note the semicolons and the quotes

Also possible with awk

ldapwhoami | awk 'NR > 3'

The above assumes that all output goes to standard output. In unix though there are two output streams that are connected to each process, the standard output (denoted with 1 - that is used for the output of the program), and the standard error (denoted with 2 - that is used for any diagnostic/error messages). The reason for this separation is that it is often desirable not to "pollute" the output with diagnostic messages, if it is processed by another script.

So for commands that generate output on both steams, if we want to capture both, we redirect the standard error to standard output, using 2>&1) like this:

ldapwhoami 2>&1 | tail -n 1

(for awk and sed the same syntax is used)

In bash, the above may be written using shorthand form as

ldapwhoami |& tail -n 1

If all you need is the standard output, and you don't care about standard error, you can redirect it to /dev/null

ldapwhoami 2> /dev/null
user000001
  • 32,226
  • 12
  • 81
  • 108