Home > Back-end >  use variable in bash function not as expected
use variable in bash function not as expected

Time:08-14

Try to print the parameter from function but print out the variable name instead of the value!

#!/usr/bin/sh

myfunc() {
    local ts=$1

    echo $ts
}

ts=`date  %s`
echo $ts

myfunc ts

Output:

1660403174
ts

The first echo value is correct, but when print in function call, it print the variable name (ts) instead of actual value!

What's proper way to get the value in function?

CodePudding user response:

When you call myfunc ts, you're passing the string ts to myfunc, not the content of the variable $ts. You probably want myfunc $ts instead.

CodePudding user response:

If the intention is to use a single function to echo the value of different variables then you may want to look at defining the function's (local) variable as a nameref, eg:

myfunc() {
    local -n ts=$1           # -n == nameref
    echo "${ts}"
}

You can then pass the name of the variable to the function, eg:

echo "########## ts1"
ts1=$(date  %s)
echo "${ts1}"
myfunc ts1

echo "########## ts2"
ts2=$(date  %Y%m%d)
echo "${ts2}"
myfunc ts2

This generates:

########## ts1
1660405189
1660405189

########## ts2
20220813
20220813

One word of caution ... if the parent process uses a variable of the same name as the function (ts in this case) you can generate a circular reference error, eg:

echo "########## ts"
ts=$(date  %s)
echo "${ts}"
myfunc ts

########## ts
1660405479
-bash: local: warning: ts: circular name reference
-bash: warning: ts: circular name reference
-bash: warning: ts: circular name reference

To address this scenario consider using a variable name (in the function) that hopefully won't be used by the caller, eg:

myfunc() {
    local -n _ts=$1          # maybe "_myfunc_local_ts" ?
    echo "${_ts}"
}

echo "########## ts"
ts=$(date  %s)
echo "${ts}"
myfunc ts

########## ts
1660405560
1660405560
  • Related