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?

2
  • Is something like: authstrings=`get-auth`; export AUTH=$authstrings[0]; export PIN=$authstrings[1] possible? Commented Nov 23, 2016 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. Commented Nov 23, 2016 at 21:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

<(...) is process substitution, not command substitution (which is $(...)).
@chepner : Too much of thinking while writing it. :) fixed now
0

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

read -d $'\4' AUTH PIN < <(get-auth)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.