LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   New line characters from command output in variable. (http://www.linuxquestions.org/questions/linux-newbie-8/new-line-characters-from-command-output-in-variable-742896/)

Coolmax 07-26-2009 10:11 AM

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

Quote:

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


$(command)
or
`command`

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,
Matthew

colucix 07-26-2009 10: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:
Code:

#!/bin/bash
var=$(cat testfile; echo c)
var=${var%??}
echo -n "lines in variable are: "
echo "$var" | wc -l

Here is the output:
Code:

$ cat testfile
line 1
line 2
line 3
line 4


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

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


All times are GMT -5. The time now is 09:33 AM.