Shell Scripting / File Handling in Shell Scripts

Reading and Writing to Files Using Redirection

This tutorial explains how to read from and write to files using redirection in shell scripts. Redirection is a powerful feature that allows data flow to be controlled, enabling t…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Focuses on reading, writing, and manipulating files within shell scripts.

Reading and Writing to Files Using Redirection

Introduction

This tutorial aims to teach you how to read from and write to files using redirection in shell scripts. Redirection is a powerful feature that allows data flow to be controlled. It enables the input and output of a program to come from and go to other programs or files.

By the end of this tutorial, you will be able to:
- Understand the concept of redirection in shell scripts
- Read from and write to files using redirection
- Apply best practices when using redirection

Prerequisites: Basic knowledge of shell scripting would be beneficial, but it's not mandatory.

Step-by-Step Guide

In shell scripts, there are three standard streams: Standard Input (stdin), Standard Output (stdout), and Standard Error (stderr). By default, stdin reads input from the keyboard, stdout prints output to the screen, and stderr prints error messages to the screen. Redirection allows you to change these defaults.

  1. Output Redirection: The '>' operator is used to redirect the output of a command to a file. If the file does not exist, it will be created. If it does exist, it will be overwritten.

Example:

echo "Hello, World!" > hello.txt

This command writes "Hello, World!" to the file hello.txt.

  1. Input Redirection: The '<' operator is used to take input from a file rather than the keyboard.

Example:

sort < file.txt

This command sorts the lines in file.txt.

  1. Appending to a file: The '>>' operator is used to append the output to an existing file.

Example:

echo "This is a new line" >> file.txt

This command adds "This is a new line" to the end of file.txt.

Code Examples

  1. Writing to a file
# This command writes "Hello, World!" to hello.txt
echo "Hello, World!" > hello.txt
  1. Reading from a file
# This command sorts the lines in file.txt
sort < file.txt
  1. Appending to a file
# This command adds "This is a new line" to the end of file.txt
echo "This is a new line" >> file.txt

Summary

In this tutorial, we covered the concept of redirection in shell scripts. We learned how to read from and write to files using the '<' and '>' operators, respectively, and how to append to a file using '>>'.

Next, you could learn about pipes, which is another powerful feature in shell scripting that works well with redirection.

Additional resources:
- Learn Shell
- Shell Scripting Tutorial

Practice Exercises

  1. Exercise 1: Write a command to redirect the output of the 'ls' command to a file named dir.txt.
  2. Solution: ls > dir.txt
  3. This command writes the output of 'ls' to dir.txt.

  4. Exercise 2: Write a command to append the current date to a file named date.txt.

  5. Solution: date >> date.txt
  6. This command adds the current date to the end of date.txt.

  7. Exercise 3: Write a command to sort the lines in a file named unsorted.txt and write the sorted lines to a file named sorted.txt.

  8. Solution: sort < unsorted.txt > sorted.txt
  9. This command sorts the lines in unsorted.txt and writes the sorted lines to sorted.txt.

Practice these exercises and modify them to get a better understanding of redirection. Happy learning!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Backlink Checker

Analyze and validate backlinks.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help