Home > Software engineering >  Pass variable to subshell created via -c option
Pass variable to subshell created via -c option

Time:01-05

I want to pass my variable to subshell process created via -c option. I have a install.sh file in which I execute the following lines and expect the printf receives $AUTOSTART_FILE value.

AUTOSTART_FILE=/etc/xdg/lxsession/LXDE-pi/autostart

sudo sh -c 'printf "@lxpanel --profile LXDE-pi\n@/home/pi/exec.sc" > $AUTOSTART_FILE'

I read and applied this answer with no success.

CodePudding user response:

You could export the variable and tell sudo to use it.

export AUTOSTART_FILE
sudo -E ....

You could serialize the variable and import in sh

... sh -c "$(declare -p AUTOSTART_FILE)"'printf %s "$AUTOSTART_FILE"'

But the best is to just pass it as an argument:

sudo sh -c 'printf "@lxpanel --profile LXDE-pi\n@/home/pi/exec.sc" > "$1"' -- "$AUTOSTART_FILE"

Or really you could just grab a tee:

printf "@lxpanel --profile LXDE-pi\n@/home/pi/exec.sc" | sudo tee "$AUTOSTART_FILE" >/dev/null
  • Related