Pectus Excavatum Pectus Excavatum - 1 year ago 105
Bash Question

Bash script CAT command uses the script parameters rather than leaving $1 in the cat'd file

I am having a bit of an issue with a bash script when trying to cat a new file.


#sudo vim /etc/init.d/glassfish

sudo cat > /etc/init.d/glassfish <<EOF

# Set path variable

# Establish Commands
case "$1" in
${GLASSFISH_HOME}/bin/asadmin start-domain domain1
${GLASSFISH_HOME}/bin/asadmin stop-domain domain1
${GLASSFISH_HOME}/bin/asadmin stop-domain domain1
${GLASSFISH_HOME}/bin/asadmin start-domain domain1
echo "usage: $0 {start|stop|restart}"
exit 0

However, when I run this script it replaces the $1 and $0 with what I used to call the script that runs the command, so $1 becomes "" and $0 becomes

Is there any way to prevent this?

Answer Source

If the here document delimiter is entirely unquoted, the contents are treated as a double-quoted string. Quote at least one character of the delimiter (it's simplest to just quote the whole thing) to have the here document treated as a single-quoted string, preventing parameter expansion.

sudo tee /etc/init.d/glassfish > /dev/null <<'EOF'

Why did I use tee instead of cat? The output redirection is not affected by sudo, since the file is opened by the shell before sudo even runs. If you need sudo because you don't otherwise have write permission to /etc/init.d/, you need to run a command like tee that opens the file itself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download