dreamsys software

UNIX & Linux Shell Scripting Tutorial

Reading & Writing Files

Reading and writing files in linux is simple, you just use the standard utilities for reading files such as cat, grep, tail, head, awk etc.. And you primarily use the output redirect operator > and standard commands like sed for writing files.

Let's say we want to write a program that interacts with a user data file called users.dat. There are several options for running this script. If the first parameter of the script is -a then it should be followed by user id, first name, last name and age, then it will write that information to the file. If the first parameter is -l then it will print out the list of user data.

#!/bin/sh

OP=$1

if [ "$1" == "-a" ]; then
	ID=$2
	FIRST=$3
	LAST=$4
	AGE=$5
	
	echo "$ID,$FIRST,$LAST,$AGE" >> users.dat
	echo "User Added"
	
elif [ "$1" == "-l" ]; then
	cat users.dat
fi

The code for this is very simple. To add a user you simple use echo to print out the fields with commas between them, then you redirect the output using the >> operator. Using the > will redirect the output STDOUT to a file and overwrite the entire file, this is why we use >> instead, because it will append to a file instead of overwriting the file. And to print out the file, we simply use the cat command, which will print out a file to the console.

Now let's add some users to have a test data set. Let's call the script users.sh.

./users.sh -a jsmith John Smith 25
./users.sh -a adoe Ann Doe 32
./users.sh -a bgates Bob Gates 17
./users.sh -a kmelvin Kay Melvin 47
./users.sh -a jgamez Joe Gamez 24
./users.sh -a msmith Mike Smith 18
./users.sh -a svai Steve Vai 42

This gave us a nice data set, so now if we want to print out the users, we can use the -l option which gives us this list of data:

jsmith,John,Smith,25
adoe,Ann,Doe,32
bgates,Bob,Gates,17
kmelvin,Kay,Melvin,47
jgamez,Joe,Gamez,24
msmith,Mike,Smith,18
svai,Steve,Vai,42

As you can see, reading and writing files in unix is simple, next we will see how to search and sort data.


Prev (Functions) | Next (Search & Sort)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6