-   Linux - Newbie (
-   -   New line characters from command output in variable. (

Coolmax 07-26-2009 09:11 AM

New line characters from command output in variable.
in man bash, section "Command Substitution" I read that new lines are removed from output:


Command Substitution
Command substitution allows the output of a command to replace the command name. There are two forms:


Bash performs the expansion by executing command and replacing the command substitution with the standard
output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they
may be removed during word splitting. (...)
Is there any way to avoid this situation and set output to variable "as is"?

Best regards,

colucix 07-26-2009 09:56 AM

The only way I know is to add an extra line and remove it later. In this way the trailing newlines are preserved since they become embedded, then you can strip the added chars using parameter substitution. This will demonstrate:

var=$(cat testfile; echo c)
echo -n "lines in variable are: "
echo "$var" | wc -l

Here is the output:

$ cat testfile
line 1
line 2
line 3
line 4

$ wc -l testfile
6 testfile
$ ./
lines in variable are: 6

The double ?? matches the added "\n" and "c".

All times are GMT -5. The time now is 11:13 PM.