Variables, entrada y salida
Aprenda a declarar variables, aceptar entradas del usuario y gestionar la salida de scripts de shell.
Variables, entrada y salida es una lección gratuita de Linux Command Line Mastery en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Linux Command Line Mastery, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Linux Command Line Mastery incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
What are Script Variables?
In shell scripting, variables are like containers for storing data. They help make your scripts flexible and reusable.
Instead of hardcoding values, you can use variables to hold information such as filenames, user inputs, or temporary results.
Declaring & Assigning Variables
To create a variable, you simply assign a value to a name. No special keyword is needed!
- Use
NAME="Coddy"(no spaces around=). - Values with spaces usually need quotes (single or double).
- Numbers don't strictly need quotes, but it's often good practice for consistency.
Accessing Variable Values
To use the value stored in a variable, you prepend its name with a $ sign.
For example, if you declared GREETING="Hello", you'd use $GREETING to get "Hello". You can also use ${VARIABLE}, which is clearer in complex situations.
Variable Naming Tips
Follow these simple rules for variable names:
- Start with a letter or underscore.
- Can contain letters, numbers, and underscores.
- Avoid using special shell keywords.
- Common practice: use uppercase for global/environment variables, lowercase for script-local ones.
Demo: Using Variables
Let's see a simple script that declares and uses a variable.
Notice how $MESSAGE retrieves the stored text.
#!/bin/bash
# Declare a variable
MY_NAME="Coddy"
GREETING="Hello"
# Access and print variables
echo "$GREETING, $MY_NAME!"
# Update the variable
MY_NAME="Learner"
echo "Nice to meet you, $MY_NAME!"Getting User Input: `read`
The read command is essential for making your scripts interactive. It waits for the user to type something and press Enter.
read VARIABLE: Stores input intoVARIABLE.read -p "Prompt: " VARIABLE: Displays a prompt before waiting for input.
Demo: Taking User Input
This script uses read -p to ask for your name and then greets you personally.
Try running it and entering your name!
#!/bin/bash
# Prompt for user's name and store it
read -p "What's your name? " USER_NAME
# Greet the user
echo "Hello, $USER_NAME! Welcome to CoddyKit."Script Output: `echo` & `printf`
You've seen echo for basic output. It simply prints its arguments followed by a newline.
For more control, printf (like in C) allows formatted output, specifying data types and alignment. It doesn't add a newline automatically, so use \n.
Demo: Input, Output & Variables
This example combines variables, user input with read, and formatted output using printf.
It calculates a simple sum based on your input.
#!/bin/bash
# Declare a base number
BASE_NUM=10
# Get a number from the user
read -p "Enter another number: " USER_NUM
# Calculate the sum
# Use $((...)) for arithmetic operations
SUM=$((BASE_NUM + USER_NUM))
# Print the result using printf for formatting
printf "The sum of %d and %d is %d.\n" "$BASE_NUM" "$USER_NUM" "$SUM"Quick Check
Consider the following shell script snippet:
#!/bin/bash
NAME="Alice"
read -p "Enter a city: " CITY
echo "Hello, $NAME from $CITY!"If the user types London and presses Enter, what will be the final output?
Recap: Variables, Input, Output
Great job! You've learned the fundamentals of shell scripting:
- Variables store data using
VAR="value". - Access variables with
$VARor${VAR}. readgets user input, often with-pfor a prompt.echoprints simple messages.printfoffers formatted output.
These are building blocks for dynamic and interactive scripts!
Preguntas frecuentes
¿La lección «Variables, entrada y salida» es gratis?
Sí — el texto completo de «Variables, entrada y salida» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Linux Command Line Mastery, actualiza a CoddyKit PRO. El curso de Linux Command Line Mastery incluye 4 lecciones en total.
¿Qué aprenderé en «Variables, entrada y salida»?
Aprenda a declarar variables, aceptar entradas del usuario y gestionar la salida de scripts de shell. Practicas Linux Command Line Mastery con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Linux Command Line Mastery?
No se requiere experiencia previa. Linux Command Line Mastery en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «Variables, entrada y salida»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Linux Command Line Mastery?
Sí. Cada lección de Linux Command Line Mastery incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Variables, entrada y salida
- Sentencias condicionales: `if`, `else`, `case`
- Bucles: `for`, `while`, `until`
- Funciones y argumentos en scripts de shell