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
4
  • how do you invoke it? Commented Feb 22, 2021 at 11:32
  • @mahatmanich I do bash some_file.sh Commented Feb 22, 2021 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. Commented Feb 22, 2021 at 13:16
  • @user1934428 valuable insight, thanks for that clarification it was really helpful Commented Feb 22, 2021 at 13:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.