Variáveis, entrada e saída
Aprenda a declarar variáveis, aceitar entradas do usuário e gerenciar a saída de scripts em scripts de shell.
Variáveis, entrada e saída é uma aula grátis de Linux Command Line Mastery no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Linux Command Line Mastery, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Linux Command Line Mastery inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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!
Perguntas Frequentes
A aula “Variáveis, entrada e saída” é grátis?
Sim — o texto completo de “Variáveis, entrada e saída” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Linux Command Line Mastery, atualize para CoddyKit PRO. O curso de Linux Command Line Mastery inclui 4 aulas no total.
O que vou aprender em “Variáveis, entrada e saída”?
Aprenda a declarar variáveis, aceitar entradas do usuário e gerenciar a saída de scripts em scripts de shell. Você pratica Linux Command Line Mastery com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Linux Command Line Mastery?
Nenhuma experiência prévia é necessária. Linux Command Line Mastery no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.
Quanto tempo leva a aula “Variáveis, entrada e saída”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Linux Command Line Mastery?
Sim. Cada aula de Linux Command Line Mastery inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Variáveis, entrada e saída
- Instruções condicionais: `if`, `else`, `case`
- Laços: `for`, `while`, `until`
- Funções e Argumentos em Scripts de Shell