Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Input and Output in Shell Scripting

This tutorial provides a comprehensive guide to handling input and output in shell scripts. Managing input and output is crucial for interacting with users and processing data efficiently in shell scripting.

1. Output to the Terminal

To display output to the terminal, use the echo command:

echo "Hello, World!"

This command prints "Hello, World!" to the terminal.

2. Reading Input from the Terminal

To read input from the user, use the read command:

read -p "Enter your name: " name
echo "Hello, $name!"

This script prompts the user to enter their name and then prints a greeting with the entered name.

3. Redirecting Output to a File

You can redirect the output of a command to a file using the > operator:

echo "This is a test." > output.txt

This command writes "This is a test." to "output.txt". If the file already exists, it will be overwritten.

To append the output to a file, use the >> operator:

echo "Appending this line." >> output.txt

This command appends "Appending this line." to "output.txt".

4. Redirecting Input from a File

You can redirect the input of a command from a file using the < operator:

while IFS= read -r line; do
    echo "$line"
done < input.txt

This script reads each line from "input.txt" and prints it to the terminal.

5. Piping Output to Another Command

You can use the | operator to pipe the output of one command to another command:

echo "Hello, World!" | tr 'a-z' 'A-Z'

This command converts the output of echo to uppercase using the tr command.

6. Handling Errors

To redirect error messages to a file, use the 2> operator:

ls nonexistentfile 2> error.log

This command attempts to list a nonexistent file, and the error message is redirected to "error.log".

To redirect both output and error messages to the same file, use the &> operator:

ls nonexistentfile &> all.log

7. Using Here Documents

A Here Document allows you to create a multiline string that can be used as input to a command:

cat << EOF
Hello, World!
This is a test.
EOF

This command prints the multiline string to the terminal using the cat command.

8. Conclusion

In this tutorial, you learned various methods to handle input and output in shell scripting, including displaying output, reading input, redirecting input and output, piping output, handling errors, and using Here Documents. Mastering these concepts will help you create more robust and interactive shell scripts.