0

I have a file which has the following text written into it -

hello h.i. b-y-e

I want to read this value into a variable. I have defined a function -

function read() { p=`cat $1`; echo "$p"; $2=`echo "$p"`; }

I get the following error -

hello h.i. b-y-e
-bash: v=hello: command not found

However, when I do -

p=`cat $filename`

text=`echo "$p"`

I have the desired string text. Can someone please explain the difference in behaviour as well as a way to acheive what I want to do.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441

1 Answers1

1

See what WordSplitting means in shell context

All you need to do to store it in a variable is,

fileContent="$(<input-file)"
printf "%s\n" "$fileContent"
hello h.i. b-y-e

(or) if you think it does not deserve 2 lines, just use a single-line as

printf "%s\n" "$(<input-file)"

(or) Using a function as

function getFileContents() {
   local input=$1
   printf "%s" "$(<input)"  
}

newVariable="$(getFileContents input-file)"
printf "%s\n" "$newVariable"
hello h.i. b-y-e

(and) if the requirement is bad enough to pass a variable to the function, something like

unset newVariable

function getFileContents() {
   local input=$1
   declare -n var=$2
   var="$(<$input)"
}

getFileContents file newVariable
printf "%s\n" "$newVariable"
hello h.i. b-y-e
Inian
  • 80,270
  • 14
  • 142
  • 161
  • I want to assign the contents of the file in the variable which was passed. That fails with your method as well. –  Jan 10 '17 at 12:40
  • @user2851669: You can reuse the logic, – Inian Jan 10 '17 at 12:41
  • This fails with `-bash: v=hello h.i. b-y-e: command not found` –  Jan 10 '17 at 12:42
  • I want to pass the variable as well in the function parameter itself. –  Jan 10 '17 at 12:53
  • like `getFileContents input-file newVariable` –  Jan 10 '17 at 12:54
  • 1
    @user2851669: This is a far better approach believe me, functions in bash do not have return string types, so what I have done is stored the function output in a new variable – Inian Jan 10 '17 at 12:55
  • You shouldn't even be using `eval` in *this* context. – chepner Jan 10 '17 at 14:38
  • 1
    Instead of `eval`: a nameref? `declare -n var=$2; var=$(< input)`, something like that? – Benjamin W. Jan 10 '17 at 15:44
  • @BenjaminW.: Appreciate it, ! and up-vote, it helps when people can provide constructive feedback like this. – Inian Jan 10 '17 at 15:51