0

I have a external program (kind of an authentication token generator) that outputs two lines, two parts of my authentication.

$ get-auth
SomeAuthString1
SomeAuthString2

Then, I want to export these strings into an environment variable, say, AUTH and PIN.

I tried several things in bash, but nothing works.

For example, I can do:

get-auth | read -d$'\4' AUTH PIN

but it fails. AUTH and PIN remain unset. If I do

get-auth | paste -d\  -s | read AUTH PIN

it also fails. The only way I can get the data is by doing

get-auth | { read AUTH; read PIN; }

but obviously only in the subshell. Exporting from that has no result

A bit of research, and I found this answer that might mean that I can't do that (reading a variable from something piped into a read). But I might be wrong. I also found that if I open a subshell with { before the read, the values are available in the subshell until I finish it with }.

Is there any way I can set environment variables from the two-line output? I obviously don't want to save that to a file, and I don't want to set up a FIFO just for that. Are those the only ways of getting that done?

Community
  • 1
  • 1
Luís Guilherme
  • 2,620
  • 6
  • 26
  • 41
  • Is something like: `authstrings=\`get-auth\`; export AUTH=$authstrings[0]; export PIN=$authstrings[1]` possible? – Gavin Nov 23 '16 at 19:00
  • 1
    Note that `{...}` does not create a subshell, just a grouped command. It is, as you discovered, the *pipe* that creates the subshell. – chepner Nov 23 '16 at 21:38

2 Answers2

3

You can use bash process-substitution, <() to achieve the same using the read command.

$ cat file
123
456

With using command-substitution properly you can retain the command output. Using read and \n as the de-limiter as;

$ read -r -d'\n' a b < <(cat file)
$ printf "%s %s\n" "$a" "$b"
123 456

Now the variables are available in the current shell, you can always export it.

Inian
  • 80,270
  • 14
  • 142
  • 161
0

The subshell was the issue. I was able to make it work by doing:

read -d $'\4' AUTH PIN < <(get-auth)
Luís Guilherme
  • 2,620
  • 6
  • 26
  • 41