1

I have this command (user is the name of my user account: echo $USER):

sudo -H -u user bash -c 'DISPLAY=:0 /usr/bin/dbus-launch /home/user/myappimage start -i &'

Work fine. Now i want to create some variables to replace my user and path appimage:

myuser="user"
pathappimage="/home/$myuser/myappimage"
sudo -H -u $myuser bash -c 'DISPLAY=:0 /usr/bin/dbus-launch $pathappimage start -i &'

The problem is variable $pathappimage does not recognize it due to the single quotes within the command.

How can I fix it ?

acgbox
  • 785

1 Answers1

0

Probably double quotes will do:

sudo -H -u $myuser bash -c "DISPLAY=:0 /usr/bin/dbus-launch $pathappimage start -i &"

or if your $pathappimage could contain spaces etc.:

… "DISPLAY=:0 /usr/bin/dbus-launch \"$pathappimage\" start -i &"
                                   ^^             ^^
# these double quotes are escaped and they will remain

In case you need single quotes for a reason, you can change a type of quotes like this:

sudo -H -u $myuser bash -c 'DISPLAY=:0 /usr/bin/dbus-launch '"$pathappimage"' start -i &'
#                          ^---- this is still treated as a single argument to bash ----^

$pathappimage will be expanded by the current shell before bash is run. If you'd like bash to see the result as double-quoted, in case you had spaces or something in $pathappimage, then invoke like this:

… 'DISPLAY=:0 /usr/bin/dbus-launch "'"$pathappimage"'" start -i &'
#                                  ^                 ^
# these double quotes are in single quotes and they will remain

or even single-quoted:

… 'DISPLAY=:0 /usr/bin/dbus-launch '\'"$pathappimage"\'' start -i &'
#                                   ^^               ^^
# these single quotes are escaped and they will remain

Another (inferior) approach. You could export the variable, pass the entire string in single quotes, then unexport if needed:

export pathappimage
bash -c 'DISPLAY=:0 /usr/bin/dbus-launch "$pathappimage" start -i &'
# bash will see the whole single-quoted string literally
export -n pathappimage

Now bash you call will expand $pathappimage, this variable will be in its environment. However sudo won't preserve the environment unless you use sudo --preserve-env, which may not be what you want or are able to do. Because of this, clever quoting is better and probably safer.