Przejdลบ do treล›ci

๐Ÿ“ฆ Variables and Environment

Variables store values for reuse within scripts or sessions. They are essential building blocks for dynamic behavior.

๐Ÿงฎ Declaring and Using Variables

Assign value to variable:

1
2
name=John
age=30

Access value using $ prefix:

1
2
echo "Name: $name"
echo "Age: $age"

Enclose in braces for clarity or disambiguation:

1
echo "${name}Doe"   # JohnDoe


๐ŸŒ Environment Variables

Environment variables are inherited by child processes:

1
2
export MYVAR=value
./some_script.sh     # inherits MYVAR

View all environment variables:

1
2
3
env
# or
printenv

Get specific one:

1
echo $HOME

Some commonly used ones: | Variable | Purpose | |----------|----------------------------| | HOME | User's home directory | | PATH | Directories searched for commands | | USER | Current username | | PWD | Present Working Directory |


๐Ÿงช Parameter Expansion

Shell supports advanced expansions:

1
2
3
4
5
6
filename="/path/to/file.txt"

basename="${filename##*/}"     # file.txt
dirname="${filename%/*}"       # /path/to
extension="${filename##*.}"    # txt
without_ext="${filename%.*}"   # /path/to/file

Pattern-based replacements:

1
2
str="hello world"
new_str=${str//o/O}            # hellO wOrld

Length of string:

1
len=${#str}                    # 11


๐Ÿงพ Summary

  • Assign variables with var=value.
  • Access them with $var or ${var}.
  • Export to make available to children.
  • Use parameter expansion for transformations.
  • Avoid spaces around = in assignments.

๐Ÿ‘‰ Continue to: Quoting