I would like to make a script which allow me to execute a command which inherit environment variables from any PID. Here the script I made :
#!/bin/sh
VARS=$(cat -A /proc/1/environ | tr "^@" "\n")
COMMAND=""
# sh compatible loop on a variable containing multiple lines
printf %s "$VARS" | while IFS='\n' read -r var
do
if [ "$var" != "" ]; then
export "$var"
fi
done
exec "$@"
I though exported variables would be available for the child process (created by exec
) but this is obviously not the case because sh my_script.sh printenv
doesn't show environment variables which are in /proc/1/environ
.
I also tried the following script :
#!/bin/sh
VARS=$(cat -A /proc/1/environ | tr "^@" "\n")
COMMAND=""
# sh compatible loop on a variable containing multiple lines
printf %s "$VARS" | while IFS='\n' read -r var
do
if [ "$var" != "" ]; then
# Replace 'VAR=var' by 'VAR="var"' for eval
# sed replace only the first occurence of the '=' due of the missing /g parameter
escaped=$(echo $var | sed -e 's/=/="/')\"
COMMAND="${COMMAND} ${escaped}"
fi
done
COMMAND="${COMMAND} $@"
eval $COMMAND
However, it looks like eval
doesn't export variables even if the evaluated command looks like VAR=value my_command
.
How I am supposed to achieve my needs ?
Thanks in advance