简体   繁体   中英

Pass variable to subshell created via -c option

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM