Культурный офтопик
 help / color / mirror / Atom feed
* [room] [tip] bash: как получить имя переменной, имя которой -- в другой переменной
@ 2007-11-08 17:12 Michael Shigorin
  0 siblings, 0 replies; only message in thread
From: Michael Shigorin @ 2007-11-08 17:12 UTC (permalink / raw)
  To: smoke-room

	Здравствуйте.
В процессе возни с бэкендом для альтераторового модуля наткнулся
на "было бы неплохо здесь взять имя переменной из другой
переменной".  Попробовал (смутно помня, что когда-то с eval и \
такое делал); спросил коллег; наконец, погуглил:

bash variable "name from variable"

=> http://www.linuxquestions.org/questions/programming-9/bash-how-to-get-variable-name-from-variable-274718/

A="abcd dcba"
B=A
C=${!B}
echo $C

A="abcd dcba"
B=A
C='eval "echo \$$B"'
eval "$C"

или как вариант --

name=a; a=1; eval echo \$$name

name=a; a=1; eval c=\$$name

Первый вариант (с ${!B}) -- явно sh/bash specific, по крайней
мере мой zsh так не смог; eval \$$name работает в sh/bash/zsh/ash.

Но этот самый вариант, судя по man bash, несколько более
навёрнутый и может пригодиться для более обширных задач:

       ${!prefix*}
       ${!prefix@}
              Expands to the names of variables whose names begin with prefix,
              separated by the first character of the IFS special variable.

       ${!name[@]}
       ${!name[*]}
              If  name  is  an  array  variable,  expands to the list of array
              indices (keys) assigned in name.   If  name  is  not  an  array,
              expands  to 0 if name is set and null otherwise.  When @ is used
              and the expansion appears within double quotes, each key expands
              to a separate word.

Может, кому-нибудь пригодится :)

-- 
 ---- WBR, Michael Shigorin <mike@altlinux.ru>
  ------ Linux.Kiev http://www.linux.kiev.ua/


^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2007-11-08 17:12 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2007-11-08 17:12 [room] [tip] bash: как получить имя переменной, имя которой -- в другой переменной Michael Shigorin

Культурный офтопик

This inbox may be cloned and mirrored by anyone:

	git clone --mirror http://lore.altlinux.org/smoke-room/0 smoke-room/git/0.git

	# If you have public-inbox 1.1+ installed, you may
	# initialize and index your mirror using the following commands:
	public-inbox-init -V2 smoke-room smoke-room/ http://lore.altlinux.org/smoke-room \
		smoke-room@lists.altlinux.org smoke-room@lists.altlinux.ru smoke-room@lists.altlinux.com smoke-room@altlinux.ru smoke-room@altlinux.org smoke-room@altlinux.com
	public-inbox-index smoke-room

Example config snippet for mirrors.
Newsgroup available over NNTP:
	nntp://lore.altlinux.org/org.altlinux.lists.smoke-room


AGPL code for this site: git clone https://public-inbox.org/public-inbox.git