Get accurate shell command output

The bash manual talks about replacing commands :

Bash executes the extension by executing the command and replacing the command submenu with the standard command output, removing any trailing lines.

Demonstration - first 3 characters, new lines:

 $ output="$(printf "\n\nx")"; echo -n "$output" | wc -c 3 

Here, the translation lines do not end and are not deleted, so the counter is 3.

Demonstration - 3 characters, last lines:

 $ output="$(printf "x\n\n")"; echo -n "$output" | wc -c 1 

Here new lines are removed from the end, so the counter is 1.

TL DR

What is a reliable workflow to get the binary output of a command into a variable?

Bourne Shell Compatibility Reward Points.

+1
source share
2 answers

The only way to do this in "Bourne compatible" is to use external utilities.

Alternatively, to type one of c, you can use xxd and expr (for example):

 $ output="$(printf "x\n\n"; printf "X")" # get the output ending in "X". $ printf '%s' "${output}" | xxd -p # transform the string to hex. 780a0a58 $ hexstr="$(printf '%s' "${output}" | xxd -p)" # capture the hex $ expr "$hexstr" : '\(.*\)..' # remove the last two hex ("X"). 780a0a $ hexstr="$(expr "$hexstr" : '\(.*\)..') # capture the shorter str. $ printf "$hexstr" | xxd -p -r | wc -c # convert back to binary. 3 

Shortened:

 $ output="$(printf "x\n\n"; printf "X")" $ hexstr="$(printf '%s' "${output}" | xxd -p )" $ expr "$hexstr" : '\(.*\)..' | xxd -p -r | wc -c 3 

The xxd command is used to convert it to a binary file.

Note that wc will not work with many UNICODE characters (multibyte characters):

 $ printf "Voilà" | wc -c 6 $ printf "★" | wc -c 3 

It will print the number of bytes, not characters.

The length of the variable ${#var} will also fail in older shells.

Of course, to run this in the Bourne shell, you must use `…` instead of $(…) .

+2
source

In bash , the form ${parameter%word} can be used ${parameter%word} Extension of shell parameters :

 $ output="$(printf "x\n\n"; echo X)"; echo -n "${output%X}" | wc -c 3 

This substitution is also indicated by POSIX.1-2008 .

0
source

Source: https://habr.com/ru/post/955282/


All Articles