How can I take STDIN and use it on the bash shell to set an environment variable? How can I take STDIN and use it on the bash shell to set an environment variable? bash bash

How can I take STDIN and use it on the bash shell to set an environment variable?


I think the best solution for that particular problem is:

export PATH=${PATH#*:}

But that doesn't answer the question of how to use stdin to set an environment variable.

It's easy to use some process' stdout:

export PATH=$(make_new_path)

But that's not strictly speaking using stdin. The obvious solution:

make_new_path | export PATH=$(cat)

won't work because the commands to the right of the pipe are executed in a subshell, so variable settings won't stick. (If it had worked, it would have been an UUOC.)

As Gordon Davisson points out in a comment, you could simply use:

read -r PATH; export PATH

Also, it is actually not necessary to export PATH, since PATH comes pre-exported, but I left it in for the case where you want to use some other environment variable.


export PATH=$(echo "$PATH" | sed -e "s|^/[A-Za-z/]*:||")

export is a shell built-in; that's why you can't execute it directly via xargs (there isn't an executable for export). This runs your edit script and sets the value as the new value of $PATH. As written with double quotes around $PATH, it works even there are multiple adjacent spaces in an element of your PATH (fairly unlikely, but no harm in making sure it works properly).


This is a bit more simple and accurate:

echo "$PATH" | sed -e s/[^:]*://

The regular expression there is more accurate, it will work even if the first segment has numbers or spaces in it.

Btw, you do NOT need to export, because PATH is already exported.

The implementation of regular expressions depends on the tool. As far as I know + does not work in sed, you can do this instead:

echo "$PATH" | sed -e 's/[^:]\{1,\}://'

It seems to me that regular expressions in sed work similar to vim and different from perl.