1

I have method that should receive string, but it does not work as intended

receive_string()
{
    local string=$1         
    echo "$string"
}

When I call it I get unrelated error.

receive_string "Catch a string my friend!"

Returns:

4: local: friend!: bad variable name

Instead of

Catch a string my friend!

What is the problem, and how to solve it?

2 Answers2

3

The problem is that variable expansion is literal in bash, so local string=$1 will behave as local string=Catch a string my friend!.

It is a good practice to enclose between double quotes your string variables, so they don't separate during expansion. Try this:

local string="$1"

It won't add quotes to your string and it will keep it together.

About the ! specific behavior, check KamilCuk's answer.

Miguel
  • 2,130
  • 1
  • 11
  • 26
3

You are not running your script with bash. You are running your script under dash shell. The behavior does not happen on bash - in bash the command local is very specially handled like ex. export and arguments have same semantics as on assignment. Most probably the shebang of your script is #!/bin/sh and sh is linked to dash on your system. Use shebang with bash to run bash.

local string=$1         

is expanding $1 so it becomes:

 local string=Catch a string my friend!

which creates a variable string with value Catch, empty variables a string and my and friend! is invalid variable value.

As always, quote variable expansion.

local string="$1"

Research when to quote variables in shell. Check your scripts with http://shellcheck.net

Side note: the ! in "something!" triggers history expansion in bash. In bash when in interactive shell with history expansion enabled, you would put it ex. in single quotes "something"'!'.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111