Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to read output of shell command

In Vim, What is the best (portable and fast) way to read output of a shell command? This output may be binary and thus contain nulls and (not) have trailing newline which matters. Current solutions I see:

  1. Use system(). Problems: does not work with NULLs.
  2. Use :read !. Problems: won’t save trailing newline, tries to be smart detecting output format (dos/unix/mac).
  3. Use ! with redirection to temporary file, then readfile(, "b") to read it. Problems: two calls for fs, shellredir option also redirects stderr by default and it should be less portable ('shellredir' is mentioned here because it is likely to be set to a valid value).
  4. Use system() and filter outputs through xxd. Problems: very slow, least portable (no equivalent of 'shellredir' for pipes).

Any other ideas?

like image 266
ZyX Avatar asked Feb 05 '12 09:02

ZyX


People also ask

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

What is $1 and $2 in shell script?

Shell scripts have access to some "magic" variables from the environment: $0 - The name of the script. $1 - The first argument sent to the script. $2 - The second argument sent to the script.

How do you pipe the output of a command to a file?

Redirect Output to a File Only To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.


1 Answers

You are using a text editor. If you care about NULs, trailing EOLs and (possibly) conflicting encodings, you need to use a hex editor anyway?

If I need this amount of control of my operations, I use the xxd route indeed, with

:se binary

One nice option you seem to miss is insert mode expression register insertion:

C-r=system('ls -l')Enter

This may or may not be smarter/less intrusive about character encoding business, but you could try it if it is important enough for you.

Or you could use Perl or Python support to effectively use popen

Rough idea:

:perl open(F, "ls /tmp/ |"); my @lines = (<F>); $curbuf->Append(0, @lines)
like image 98
sehe Avatar answered Oct 02 '22 16:10

sehe