Working with Files in Shell Scripts

Tutorial 2 of 5

Working with Files in Shell Scripts

1. Introduction

1.1 Tutorial's Goal

This tutorial will teach you how to manipulate files in shell scripts. It covers the basics of file handling, including reading, writing, and deleting files.

1.2 Learning Outcomes

By the end of this tutorial, you will understand how to:

  • Read from files
  • Write to files
  • Delete files

1.3 Prerequisites

Basic knowledge of shell scripting is required.

2. Step-by-Step Guide

Shell scripts provide several commands for file handling, including cat for reading, > for writing, and rm for deleting.

2.1 Reading Files

To read a file, use the cat command followed by the file name:

cat fileName

2.2 Writing Files

To write to a file, use the > operator. It will overwrite the file if it exists, or create a new file if it doesn't:

echo "Hello, World!" > fileName

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

echo "Hello again, World!" >> fileName

2.3 Deleting Files

To delete a file, use the rm command:

rm fileName

3. Code Examples

3.1 Reading from a File

# This script reads a file
fileName='test.txt'
cat $fileName

3.2 Writing to a File

# This script writes to a file
fileName='test.txt'
echo "Hello, World!" > $fileName

3.3 Appending to a File

# This script appends to a file
fileName='test.txt'
echo "Hello again, World!" >> $fileName

3.4 Deleting a File

# This script deletes a file
fileName='test.txt'
rm $fileName

4. Summary

In this tutorial, you have learned how to read, write, and delete files in shell scripts. The next step could be learning about file permissions and how to change them.

5. Practice Exercises

5.1 Exercise 1

Write a script that creates a file and writes the numbers 1 to 10 in it.

5.2 Exercise 2

Write a script that reads the file created in Exercise 1 and displays the numbers in reverse order.

5.3 Tips for Further Practice

Try to handle different types of files, such as binary files or directories.