66 links
  • Ban's links
  • Home
  • Login
  • RSS Feed
  • ATOM Feed
  • Tag cloud
  • Picture wall
  • Daily
Links per page: 20 50 100
  • Importing another process' environment (bash)

    To import the environment of another process, one can use while read -d '' -r ev; do export "$ev"; done <"/proc/$(pgrep -u "$USER" -x PROCNAME)/environ" (when using bash).

    This is particularly handy e.g. when connecting to a machine through SSH while a graphical session is running and wanting to interact with it (X, DBus, etc.).

    This leverages some Bash specifics, like read -d '' to use NUL as the line separator. There are solutions only using POSIX constructs, but the only I know involves a temporary file, which is not as handy. Before discovering read -d '' I was using another Bashism: process substitution, in the form of <(tr '\0' '\n' </proc/$(pgrep -u "$USER" -x PROCNAME). It isn't as good as it would not properly handle newlines in the environment, though, but it could easily be converted to a POSIX-compliant construct using a temporary file. Note that the naive alternative of piping the same thing to the while loop (and thus to read) will not work as it would run the loop in a subshell, not affecting the environment of the current shell. Another alternative would be to evaluate the output of such a subshell that would echo it, but that would require escaping the values, to which I don't know a robust POSIX solution (there are plenty of handmade ones around, but most fail in odd corner cases -- and no, printf %q is not in POSIX).

    May 11, 2022 at 21:50:00 GMT+2 * - permalink -
    QRCode
    - https://ban.netlib.re/shaarli/shaare/xJy3dg
    bash shell linux
Links per page: 20 50 100
Shaarli - The personal, minimalist, super fast, database-free, bookmarking service by the Shaarli community - Help/documentation