Ana Sayfa / Linux / Bash Script / Bash Parameter Expansion

Bash Parameter Expansion

The $ character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.

Modifying the case of alphabetic characters

Version ≥ 4.0

To uppercase

$ v="hello"
# Just the first character
$ printf '%s\n' "${v^}"
Hello
# All characters
$ printf '%s\n' "${v^^}"
HELLO
# Alternative
$ v="hello world"
$ declare -u string="$v"
$ echo "$string

To lowercase

$ v="BYE"
# Just the first character
$ printf '%s\n' "${v,}"
bYE
# All characters
$ printf '%s\n' "${v,,}"
bye
# Alternative
$ v="HELLO WORLD"
$ declare -l string="$v"
$ echo "$string"
hello world

Toggle Case

$ v="Hello World"
# All chars
$ echo "${v~~}"
hELLO wORLD
$ echo "${v~}"
# Just the first char
hello World

Length of parameter

# Length of a string
$ var='12345'
$ echo "${#var}"

Note that it’s the length in number of characters which is not necessarily the same as the number of bytes (like in UTF-8 where most characters are encoded in more than one byte), nor the number of glyphs/graphemes (some of which are combinations of characters), nor is it necessarily the same as the display width.

# Number of array elements
$ myarr=(1 2 3)
$ echo "${#myarr[@]}"
3
# Works for positional parameters as well
$ set -- 1 2 3 4
$ echo "${#@}"
4
# But more commonly (and portably to other shells), one would use
$ e

Replace pattern in string

First match:

$ a='I am a string'
$ echo "${a/a/A}"
I Am a string

All matches:

$ echo "${a//a/A}"
I Am A string

Match at the beginning:

$ echo "${a/#I/y}"
y am a string

Match at the end:

$ echo "${a/%g/N}"
I am a strinN

Replace a pattern with nothing:

$ echo "${a/g/}"
I am a strin

Add prefix to array items:

$ A=(hello world)
$ echo "${A[@]/#/R}"
Rhello Rworld

Bunada Göz Atın

PHP Types

Type Comparison There are two types of comparison: loose comparison with == and strict comparison …

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir