Working with Files in Shell Script - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Working with Files in Shell Script

Share This

In this chapter, we will discuss some commands which are very important to work with files.

ls shows the list of files in a directory
cat views the content of a file
wc counts words, lines, and characters in a file
cp copies file(s)
mv moves file(s)
rm removes file(s)

File listing

The list of files is shown by the ls command. To get details of files long listing is used. For long listing ls -l command is used. In some systems, ll, as an alias of ls -l, works for long listing.

Viewing Content of a File

To show the content of a file cat command is used.

Numbering the lines of the file.

Copying Content of a File

To copy the content of a file into another file cp is used. The first argument of this command is the name of the source file and the second argument is the name of the target file.

A shell script file can be written as follow.

#!/bin/bash echo Enter the name of the source file read srcfile echo Enter the name of the target file read tarfile cp srcfile tarfile

Moving File(s)

If you want to move a file to another location or to rename a file mv command is used. The first argument is file name (you want to move) and the second argument is destination location or destination with target file name.


#!/bin/bash echo Enter the name of the file to move read file echo the destination location read destloc mv file destloc

Removing File(s)

To remove the file(s), the rm command is used.


#!/bin/bash echo Enter the name of the file to remove the read file rm file




Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.