How to read a file into a variable and print it using that variable with exact format in shell

1k views Asked by At

I am trying to read to id_rsa file into a variable var( set var=`cat id_rsa`) in tcsh to provide input to a program. But when i echo the variable ( echo "$var")new lines are gone, its a one line file content. So how do i correctly store and print the variable?

1

There are 1 answers

0
Greg Nisbet On

Don't use tcsh for this task, getting the output of a command into a variable in verbatim is unnecessarily difficult:

Some workarounds if you have to use tcsh are:

use redirection

% yourtool < id_rsa

Store the variable as base-16 (or something else) encoded stuff, so that it doesn't contain any newline characters that will get mangled by tcsh.

% set hex_contents = `<id_rsa xxd -l 16 -p`

Use a tempfile?

% set tempfile = `mktemp`
% program > tempfile

... later

% <tempfile other-program

I asked a similar question almost a year ago; https://unix.stackexchange.com/questions/284220/tcsh-preserve-newlines-in-command-substitution

In case you're curious this is how you get the verbatim contents (credit Stéphane Chazelas).

set temp = "`(some command; echo .) | paste -d . - /dev/null`"
set var = ""
set nl = '\
'
foreach i ($temp:q)
  set var = $var:q$i:r:q$nl:q
end
set var = $var:r:q