简体   繁体   中英

Escape quotes inside su -c

I would like to pass a path potentially containing whitespace into an su -c command inside a .sh script:

su -c "xdg-desktop-menu install ${DesktopFile}" -m "${Username}"

$DesktopFile is my path that needs to get escaped. I tried many variations with ' inside "" , with \\" and several braces, but I have not come up with a solution. Interestingly enough, xdg-desktop-icon works fine, but xdg-desktop-menu dies at the whitespace. Any suggestions?

If you're using bash, printf '%q' can be used to escape special characters when quoting is insufficient.

su -c "xdg-desktop-menu install $(printf '%q' "$DesktopFile") -m $(printf '%q' "$Username")"

Notice that $(printf...) doesn't need quotes, but "$DesktopFile" does. The variable needs to be passed to printf safely, so it has to be quoted. printf '%q' 's output is guaranteed to be immune to word splitting and globbing, so it doesn't need quotes. (Although, if you wanted to quote it, you could. It would need \\" on either side.)

i can't make out if this is a bug in xdg-desktop-menu, since it works in xdg-desktop-icon, nevertheless there is a workaround I am now using:

cd "$PathWithSpaces"
su -c "xdg-desktop-menu install $DesktopFilenameWithoutSpaces" -m "$Username"

PathWithSpaces contains DesktopFilenameWithoutSpaces , seems to work reliably.

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