</>
Skip to content
Bash lessons (18/29)

Bash — Input and Output

Reading input

#!/bin/bash

# Basic input
read -p "Enter name: " name
echo "Hello, $name!"

# Silent input (for passwords)
read -sp "Enter password: " pass
echo

# With timeout
read -t 5 -p "Quick! Enter something: " input

Output redirection

#!/bin/bash

# Redirect stdout
echo "Hello" > file.txt      # Overwrite
echo "World" >> file.txt     # Append

# Redirect stderr
command 2> error.txt

# Redirect both
command > output.txt 2>&1
command &> output.txt

Here documents

#!/bin/bash

cat << EOF
Name: Alice
Age: 30
City: NYC
EOF

# With variable expansion
cat << EOF
Today is $(date)
User is $USER
EOF

File reading

#!/bin/bash

# Read entire file
content=$(cat file.txt)

# Read line by line
while IFS= read -r line; do
    echo "$line"
done < file.txt

Piping

#!/bin/bash

# Pipe output to next command
ls -la | grep ".txt" | wc -l

# Process substitution
diff <(ls dir1) <(ls dir2)

Mini Practice

Write Bash code that:

  1. Reads user input with read
  2. Redirects output to a file
  3. Uses a here document
  4. Reads a file line by line

Up Next

In the next lesson, you'll learn about Pipes — chaining commands together.

Related Topics

Frequently Asked Questions about Input and Output

What is Input and Output in Bash?

Input and Output is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Input and Output?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Input and Output.

Why is Input and Output important in Bash?

Input and Output is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.