9 Ocak 2019 Çarşamba

bash variable expansion - Değişkenin Değerine Erişmek - "$variable" Şeklinde

Giriş
$ karakteri bir değişkenin başına gelirse variable expansion olur. Eğer $ karakteri başta değilse başka bir anlama gelir. Açıklaması şöyle
$ does not have a special meaning by itself (try echo $), only when combined with other character after it and forming an expansion, e.g. $var (or ${var}), $(util), $((1+2)).
$ karakterinine sonda olması ile ilgili bazı örnekler şöyle.
echo ab$: literal output, fully specified
echo a$ b: literal output, fully specified
echo a$ b$: literal output, fully specified
echo a$b: expansion of parameter b, fully specified
echo a$-b: expansion of special parameter -, fully specified
echo a$+b: unspecified behaviour
echo "a$ b": unspecified behaviour
Değişkenlerin "$var" şeklinde yani tırnak içinde kullanılması gerekir. Böylece empty words yani boş stringler de işlenir. Açıklaması şöyle
double-quote any expression involving a $VARIABLE, at least if one wanted it to be interpreted by the shell as one single item, otherwise, any spaces in the content of $VARIABLE would throw off the shell.
Örnek
Sıkça yapılan bir hata şöyle.
rm -- $line  # <- no double quotes to expand wildcards
Örnek
Şöyle yaparız.
$ args() { echo "got $# arguments"; }
$ var=""
$ args $var
got 0 arguments    //var has empty word
$ args "$var"
got 1 arguments
Örnek
"${!var}" şeklinde kullanırsak pointer gibi çalışır. Şöyle yaparız.
$ var=test
$ test="my string"
$ echo "$var"
test
$ echo "${!var}"
my string

Hiç yorum yok:

Yorum Gönder