Is there a way to use a variable to get a given parameter?

function f(){ i=1; echo "${!i}" ; }
f a b

Output: a

function f(){ i=1; echo "${!((i+1))}" ; }
f a b

Conclusion: The bash: ${!((i+1))}: bad substitutionoutput I want isb

What is the correct syntax?

+4
source share
2 answers

In addition to the helpful codeforester answer :

If you only need to access the positional parameters in your function, you can use the array syntax to extract the parameter of interest; array cutting syntax supports arithmetic expressions:

> function f(){ i=1; echo "${@: i+1 : 1}" ; }; f a b
b
+3
source

It looks like Bash doesn't allow expressions in a variable indirectness. How about increasing the value ibefore using it in a parenthesis extension, for example:

function f() { i=2; echo "${!i}"; }

Bash:

${! prefix *} ${! prefix @}

, , IFS. "@", , .

+3

Source: https://habr.com/ru/post/1672974/


All Articles