0

I have the following code in shell

#!/bin/sh

function myfunc
{
   $1=3
   echo "myvar = $myvar"
}

myfunc myvar

expected result: myvar = 3

so basically what the script must do is this.

I will be calling the function and give it an argument. I want to declare that argument INSIDE the function. In other words, I choose the name of the variable when I call the function.

But it doesn't work...

1 Answer 1

1

Any of the following will work:

let $1=3
export $1=3
local $1=3
eval $1=3

Note that some of these alternatives have side effect, more specifically regarding the visibility of the variable.

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

3 Comments

This worked !!!!! But is it possible to know why it's working? What does export do exactly? How can it be used except in these situations?
Well, put simply, this is due to the parsing rules of the shell. The parser either try to match the pattern "<variable_name>=<value>" or a command expression. Variable substitution are not acceptable in production rule "<variable_name>", so "$var=12 34 45", after variable substitution, will be interpreted as the name of a program to be executed (something like "bar=12", with argument "34" and "45").
As for the "export" buit-in command, in both allocate a value to a variable, and mark the variable to be exported, that is, copied to child processes' environment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.