Home > Mobile >  Linux Bash: how to put value of $var into "$" to make it $($var) with $var bigger than 9?
Linux Bash: how to put value of $var into "$" to make it $($var) with $var bigger than 9?

Time:10-29

I need to $ be a function of variable $a, so $($a) would be equal $value_of_a (so there would be possible to print OPTIONS of a command under number "a").

For example: if a=5 I need that bash make a call to the $5 ($5 is the OPTION5 that was when the program was typed into the Terminal; for example in

./hello.sh qq ww ee rr tt 

the "tt" is the option №5), so I need

echo $5

but I don't know how to make it work through a and not through typing $5 manually

I've tried something like this

"${$a}"

this

"${0 $a}"

and later on even found eval:

eval b=( '$'"$a" )

so calling $b places in $b's place "$-->value_of_a_here<--"

but eval gives only first digit, so if a=11 then $b prints OPTION1|1, as it would be $1 (with adding 1 as a string) and not $11.

So if there would be

./hello.sh q w e r t y u i o p g
a=11
eval b=( '$'"$a" )
echo $b

then output would be

q1

and not the

g

It seems that bigger that $9 one can't make it at all. Is it possible? (and I heard that 1 line of a command with its sending OPTIONS is limited by 32 bytes, or something about so; maybe it is here?)

Could anyone help?

CodePudding user response:

You need to use braces to access positional parameters above 9.

Also, bash uses special syntax for indirection:

$ set -- q w e r t y u i o p g
$ echo $11
q1
$ echo ${11}
g
$ a=11
$ echo $a
11
$ echo ${$a}
bash: ${$a}: bad substitution
$ echo ${!a}
g
$

The 32 byte limit you read about may be referring to the "bang path". I can't currently find the definitive reference but the Perl documentation states:

historically some operating systems silently chopped off kernel interpretation of the #! line after 32 characters

CodePudding user response:

Use an associative array, something like this.

#!/usr/bin/env bash

alpha=({a..z})
args=("$@")

declare -A input
for arg in "${!args[@]}"; do
  input["${alpha[$arg]}"]="${args[$arg]}"
done

declare -p input

With your approach, this might do it.

#!/usr/bin/env bash

n=1
declare -A a

for arg; do
  a[$((n  ))]="$arg"
done

declare -p a

printf '%s\n' "${a[11]}"

Run that script against your arguments.

my_script q w e r t y u i o p g

output

declare -A a=([9]="o" [8]="i" [7]="u" [6]="y" [5]="t" [4]="r" [3]="e" [2]="w" [1]="q" [10]="p" [11]="g" )

g
  • Related