-1

The file myfile.sh looks like this:

echo "hello"








The file I run looks like this:

a=$(cat myfile.sh)
echo $a

When I run the file, I only get the output:

echo "hello"

And not what the actual file content is. What's going on here?

mehtaarn000
  • 116
  • 3
  • 11

2 Answers2

1

http://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html

In a=$(cat myfile.sh) your variable gets assigned

the standard output of the command, with any trailing newlines deleted

And that is where your extra lines went.

0

From the man page for dash (/bin/sh) on my system,

The shell expands the command substitution by executing command in a subshell environment and replacing the command substitution with the standard output of the command, removing sequences of one or more ⟨newline⟩s at the end of the substitution. (Embedded ⟨newline⟩s before the end of the output are not removed; however, during field splitting, they may be translated into ⟨space⟩s, depending on the value of IFS and quoting that is in effect.)

(Emphasis mine.)

You could use the following:

#!/bin/sh

LF='
'

a=
while read -r line; do
   a="$a$line$LF"
done

printf -- '--\n%s--' "$a"

Test:

$ printf 'a   b   c\nd\n\n\ne\n\n\n' | ./a.sh
--
a   b   c
d


e


--
ikegami
  • 343,984
  • 15
  • 249
  • 495