Інтерполяція рядків

Інтерполяція рядків

How to: (Як це зробити:)

In Bash, place the variable name inside ${} or directly after a $ within double quotes.

# Basic variable interpolation
echo "Hello, $name!"

# Using braces for clarity or when needed
greeting="Hello, ${name}!"
echo $greeting


Hello, Olena!
Hello, Olena!

To combine variables or include a variable next to other characters without spaces:

# Concatenate variables
action="logged in"
echo "$user$action"

# Variable with a suffix
echo "You have ${file_count} files."


Olena logged in
You have 3 files.

Deep Dive (Поглиблений огляд)

String interpolation is not unique to Bash; it’s a feature of many programming languages, used since the early days to ease code readability and functionality. In Bash, unlike languages like PHP or Perl, you don’t need a special syntax (like . or ,) to concatenate strings and variables; instead, it’s mainly a feature of how the shell expands variables within strings. As an alternative to direct interpolation, you might use command substitution (using the $(...) syntax) to place command output directly into a string.

# Command substitution example
echo "The date is $(date)."

In terms of performance, interpolation may be slightly faster than other techniques, like multiple echo statements or the concatenation of variables using command substitution, because it’s handled directly by the shell’s parser. But remember, with great power comes great responsibility – interpolating user input directly can lead to security issues like injection attacks unless properly sanitized.

See Also (Дивіться також)

For more details and best practices, here are some useful resources: