Search code examples
bashshellsuse

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.

#!/bin/bash


#sudo vim /etc/init.d/glassfish

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

# Set path variable
GLASSFISH_HOME=/opt/glassfish3

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

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 testscript.sh

Is there any way to prevent this?


Solution

  • 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'
    ...
    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.