简体   繁体   中英

Linux bash command with quotes - inside quotes - inside quotes

I have this command that runs fine - mysql -p$DB_PW -u ops --host="$DB_ENDPOINT" -e "delete from users.webservers where ipaddress='$PRIVATE_IP';"

I want to run it with a different user so I have to put the command inside single quotes but it then will now work -

sudo -H -u ernie bash -c 'mysql -p$DB_PW -u ops --host="$DB_ENDPOINT" -e "delete from users.webservers where ipaddress='$PRIVATE_IP';"'

Any help is appreciated!

You don't need to run bash ; sudo will run mysql just fine.

sudo -H -u ernie \
    mysql -p"$DB_PW" \
          -u ops \
          --host="$DB_ENDPOINT" \
          -e "delete from users.webservers where ipaddress='$PRIVATE_IP';"

Note that there is a risk of a SQL injection attack; be sure you know what the value of PRIVATE_IP is before executing this command.

Your second layer of quotes ( " ) will have no problems being nested inside ' quotes. Your most nested layer must be escaped. To escape single quotes, use

'\''

instead of '

Technically, this is not escaping single quotes, this is ending the previous quoted section, writing a literal ' , and then starting a new quoted section. This is how bash is designed to handle single quotes that must be nested inside other single quotes.

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