2

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
Inder
  • 3,711
  • 9
  • 27
  • 42
  • how do you invoke it? – mahatmanich Feb 22 '21 at 11:32
  • @mahatmanich I do bash some_file.sh – Inder Feb 22 '21 at 11:32
  • 1
    @Inder : The HERE-document is basically like a double-quoted string and undergoes parameter expansion. Hence, `$1` is already expanded before _sudo_ is invoked. If you would call it as `bash some_file.sh FOO`, you would see the effect of the expansion better. – user1934428 Feb 22 '21 at 13:16
  • @user1934428 valuable insight, thanks for that clarification it was really helpful – Inder Feb 22 '21 at 13:42

1 Answers1

3

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278