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:
system()
. Problems: does not work with NULLs.:read !
. Problems: won’t save trailing newline, tries to be smart detecting output format (dos/unix/mac).!
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).system()
and filter outputs through xxd
. Problems: very slow, least portable (no equivalent of 'shellredir'
for pipes).Any other ideas?
$? 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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With