2

Is it possible to first pass a parameter to the function and than change its value?

#!/bin/bash

name=old_name

echo $name #echoes "old_name"

alter () {
$1=new_name #throws error that says 'command not found'
}

alter name

echo $name #I would like to see "new_name" here

2 Answers 2

4

Yes, using a nameref:

alter () {
    declare -n foo=$1
    foo=new_name
}

See Bash FAQ 006 for more advice and warnings, as well as workarounds for versions of bash that predate nameref support (i.e., 4.2 or earlier).

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

Comments

0

You can't do it that way, unfortunately. Also, bash functions can't return values. The usual options are (1) set a global var in the function (yuck), or (2) echo the "return" value and use command substitution to call it. Something like this:

alter () {
  echo "$1 but different"
}

name="Fred"
name=$(alter $name)
echo Name is now $name

returns: Name is now Fred but different

1 Comment

Not really what I was looking for but thanks for the effort. I up voted this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.