Advanced Parameter Expansion Techniques
Indirect Parameter Expansion
Bash parameter expansion also supports indirect expansion, which allows you to use the value of a variable as the name of another variable:
## Define some variables
MAIN_VAR="value1"
VAR_NAME="MAIN_VAR"
## Indirectly access the value of MAIN_VAR
INDIRECT_VALUE="${!VAR_NAME}"
echo "$INDIRECT_VALUE" ## Output: value1
Conditional Expansion
You can use parameter expansion to conditionally execute commands or set values based on the state of a variable:
## If the variable is set, use its value, otherwise use a default
OUTPUT_FILE="${OUTPUT_FILE:-/tmp/output.txt}"
## If the variable is not null, execute a command
[ -n "$BACKUP_DIR" ] && tar -czf "${BACKUP_DIR}/backup.tar.gz" /data
Array Manipulation
Bash parameter expansion can also be used to work with array variables:
## Define an array
FILES=("file1.txt" "file2.txt" "file3.txt")
## Get the length of the array
NUM_FILES="${#FILES[@]}"
## Access individual array elements
FIRST_FILE="${FILES[0]}"
LAST_FILE="${FILES[-1]}"
## Extract a range of array elements
MIDDLE_FILES=("${FILES[@]:1:$((${#FILES[@]} - 2))}")
Nested Expansions
Parameter expansions can be nested to create more complex transformations:
## Extract the base name of a file with a specific extension
FILE_PATH="/path/to/example.txt"
BASE_NAME="${FILE_PATH##*/}"
FILE_EXT="${BASE_NAME##*.}"
BASE_NAME="${BASE_NAME%.*}"
echo "$BASE_NAME" ## Output: example
By combining these advanced techniques, you can create powerful and flexible Bash scripts that can handle a wide range of data manipulation tasks.