简体   繁体   中英

echo quotes in bash script

I'm creating an automatic network configuration script and in it i have

#!/bin/bash
sudo rm /etc/default/ifplugd  
sudo echo "INTERFACES=""
HOTPLUG_INTERFACES="wlan0 eth0"
ARGS="-q -f -u0 -d10 -w -I"
SUSPEND_ACTION="stop"" > /etc/default/ifplugd

however on viewing /etc/default/ifplugd some of the quotes are missing

INTERFACES=
HOTPLUG_INTERFACES=wlan0 eth0
ARGS=-q -f -u0 -d10 -w -I
SUSPEND_ACTION=stop

How do I configure the script so it includes the quotes between the first and last echo ones?

How about:

sudo sh -c 'cat <<END >/etc/default/ifplugd
INTERFACES=""
HOTPLUG_INTERFACES="wlan0 eth0"
ARGS="-q -f -u0 -d10 -w -I"
SUSPEND_ACTION="stop"
END
'

You don't need to explicitly rm , the > redirection will truncate the file before writing the new content.

You need to escape the " marks with a \\ prefix, like this:

#!/bin/bash
sudo rm /etc/default/ifplugd  
sudo echo "INTERFACES=\"\"
HOTPLUG_INTERFACES=\"wlan0 eth0\"
ARGS=\"-q -f -u0 -d10 -w -I\"
SUSPEND_ACTION=\"stop\"" > /etc/default/ifplugd

A heredoc provides an elegant solution:

sudo tee << EOF /etc/default/ifplugd
INTERFACES=""
HOTPLUG_INTERFACES="wlan0 eth0"
ARGS="-q -f -u0 -d10 -w -I"
SUSPEND_ACTION="stop"
EOF 

This way, you don't have to manually quote each and every "" around, and you are not removing the ifplugd file, so you won't need to reset permissions after creating it.

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