Técnicas Avanzadas de Valores Predeterminados
Ahora que comprende los conceptos básicos de la configuración de valores predeterminados en Bash, exploremos algunas técnicas avanzadas que harán que sus scripts sean aún más potentes y flexibles.
El Operador de Asignación :=
El operador := no solo sustituye un valor predeterminado, sino que también asigna ese valor a la variable si no estaba establecida. Esto es útil cuando desea que la variable conserve su valor predeterminado para un uso posterior.
- Cree un nuevo archivo llamado
assign_default.sh en el directorio bash_defaults con el siguiente contenido:
#!/bin/bash
## Demonstrate the := assignment operator
echo "Before assignment, NAME = $NAME"
## This assigns the default value to NAME if it's unset
: ${NAME:="DefaultUser"}
echo "After assignment, NAME = $NAME"
## Now use the variable in a function
greet() {
echo "Hello, $NAME!"
}
greet
- Haga que el script sea ejecutable:
chmod +x assign_default.sh
- Ejecute el script sin establecer NAME:
./assign_default.sh
Debería ver:
Before assignment, NAME =
After assignment, NAME = DefaultUser
Hello, DefaultUser!
- Ahora establezca NAME antes de ejecutar:
NAME="Alice" ./assign_default.sh
Debería ver:
Before assignment, NAME = Alice
After assignment, NAME = Alice
Hello, Alice!
Encadenamiento de Valores Predeterminados
A veces, es posible que desee verificar múltiples fuentes para obtener un valor antes de recurrir a un valor predeterminado codificado. Puede encadenar valores predeterminados para lograr esto:
- Cree un nuevo archivo llamado
chain_defaults.sh en el directorio bash_defaults con el siguiente contenido:
#!/bin/bash
## Read config file if it exists
if [[ -f "./user.conf" ]]; then
source "./user.conf"
fi
## Chain default values: command line arg -> config file -> environment var -> hard-coded default
USERNAME=${1:-${CONFIG_USER:-${USER:-"guest"}}}
LANGUAGE=${2:-${CONFIG_LANG:-${LANG:-"en_US"}}}
echo "Hello, $USERNAME! Your language is set to $LANGUAGE."
- Haga que el script sea ejecutable:
chmod +x chain_defaults.sh
- Cree un archivo de configuración para probar:
echo "CONFIG_USER=ConfigUser" > user.conf
echo "CONFIG_LANG=es_ES" >> user.conf
- Pruebe el script con diferentes combinaciones:
## Use defaults from the config file
./chain_defaults.sh
## Override with command line arguments
./chain_defaults.sh CommandLineUser fr_FR
## Remove config file to test falling back to environment variables
rm user.conf
./chain_defaults.sh
Valores Predeterminados Condicionales
También puede usar expresiones condicionales para establecer diferentes valores predeterminados según las condiciones:
- Cree un nuevo archivo llamado
conditional_defaults.sh en el directorio bash_defaults con el siguiente contenido:
#!/bin/bash
## Get the current hour (24-hour format)
HOUR=$(date +%H)
## Set default greeting based on time of day
if ((HOUR < 12)); then
DEFAULT_GREETING="Good morning"
elif ((HOUR < 18)); then
DEFAULT_GREETING="Good afternoon"
else
DEFAULT_GREETING="Good evening"
fi
## Use the conditional default if no greeting is provided
GREETING=${1:-"$DEFAULT_GREETING"}
NAME=${2:-"User"}
echo "$GREETING, $NAME!"
echo "The current time is $(date +%H:%M)."
- Haga que el script sea ejecutable:
chmod +x conditional_defaults.sh
- Ejecute el script para ver cómo elige un saludo predeterminado según la hora del día:
./conditional_defaults.sh
- Anule el saludo predeterminado:
./conditional_defaults.sh "Hello" "World"
Estas técnicas avanzadas le brindan más flexibilidad al trabajar con valores predeterminados en Bash, lo que le permite crear scripts más sofisticados y fáciles de usar.