1

If I pass variable as a positional argument to a function, is it possible to determine the name of the variable used from inside the function, or I can only access its value?

I have a function envir-export that I can use to define an environment variable and store it in a special environment file that would then get sourced.

envir-export ()
 {
  nm="$1"
  vl="$2"
     
  envirs_trkrc="${HOME}/Opstk/envirs"
  echo "export ${nm}=${vl}" >> ${envirs_trkrc}/envirs.rc

  source ${envirs_trkrc}/envirs.rc
  echo "$nm exported with value $vl"
 }

Currently I am using by the following call

envir-export VERBOS 8

Using the name VERBOS with value 8.

I would like to improve on this function, both in convenience, and also functionally.

For instance, if no value is supplied then I only export the name with a value being assigned.

0

1 Answer 1

0

Common practice for achieving this is do something like

function envir-export () {
  name="${1%%=*}"
  value="${1##*=}"
  echo 'the name is '"$name"
  echo 'the value is '"$value"
}

envir-export VERBOS=8



$ function f () { name="${1%%=*}" ; value="${1##*=}" ; echo name "$name" ; echo value "$value" ; } ; f VERBOS=8
name VERBOS
value 8
$

Check the bash manpage and search for 'Parameter Expansion' for a howto on splitting the input into name and value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.