Sopalajo de Arrierez
Sopalajo de Arrierez

Reputation: 3860

Linux shell scripting: Is it possible to modify the variable sent as parameter to a function?

I am a bit new to linux shell scripting, so this could be a very silly question.

This is a simple example code (of course it does not work, but I am hoping to show what I wanna do):

#!/bin/bash 
function AppendLetters() {
  # Value sent as parameter: $1
  $1= "$1"LLL
}
var="foo"
AppendLetter $var
echo "$var"

So, when calling the program from command line:

$ ./example.sh

I would like to modify the internal variableobtain some sort of:

fooLLL

Reason for doing this: I have a script that loads multiple variables from a config file, and would like to make the same modification to that variables in order to use them in my program.

Is it possible? Can a function modify variables sent as parameter?

Upvotes: 2

Views: 157

Answers (2)

anubhava
anubhava

Reputation: 785196

Starting from Bash 4.3.0 you can use declare -n to get reference of a variable in a function:

AppendLetters() {
   declare -ln ref="$1"
   ref+="LLL"
}

var="foo"
AppendLetters "var"

echo "$var"
fooLLL

From help declare:

-n  make NAME a reference to the variable named by its value

EDIT: Thanks to @gniourf_gniourf for suggesting this printf, you can do this in older BASH:

AppendLetters() { printf -v "$1" '%sLLL' "${!1}"; }

var="foo"
AppendLetters "var"

echo "$var"
fooLLL

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246827

Without needing bash 4.3, using variable indirection:

AppendLetters() {
  declare -g "$1"="${!1}LLL"
}

var=f00
AppendLetters var
echo "$var"
f00LLL

The -g option for declare is necessary so that the assignment is not treated as local to the function.


Given:

I have a script that loads multiple variables from a config file, and would like to make the same modification to that variables in order to use them in my program.

I would do this, not in a function, using bash's += assignment operator

varlist=( var1 var2 var3 )
for varname in "${varlist}"; do
    declare "$varname"+="LLL"
done

Upvotes: 2

Related Questions