bash script within EOF unable to pass arguments to function

Viewed 641

I have the following bash script, it is running in a file named some_file.sh, the contents look like

sudo -i -u $USER bash << EOF


func(){
    echo $1

}

func 'Test message for channel'

EOF

This returns nothing in the argument for the function even though the function is invoked with an argument, what am I doing wrong?

To invoke it I do

bash some_file.sh
1 Answers

Quote the << 'EOF' to prevent the $ in the function from being expanded before the function is defined.

sudo -i -u $USER bash << 'EOF'

func(){
    echo $1
}

func 'Test message for channel'

EOF

See the Bash manual on Here Documents. This behaviour applies to all Bourne shell derivatives — Bash, POSIX shells, ksh, etc.

Related