Linux Tutorial - File Related Commands
Many different operations can be performed on files. Some of the most basic ones are
documented here.
1. List Files
We'll start by checking which files exist in our current directory. The ls command
is used for this.
machine:~$ ls
mydata.zip mydirectory/ myfile.txt
|
|
This yields three results. Note that the ls command has many
options which determine what results are shown and how those are formatted.
One example :
machine:~$ ls -1
mydata.zip
mydirectory/
myfile.txt
|
|
For a list of available options and usage help for Linux commands, see
the more help tutorial section.
2. What Type Of File Is This?
The ls command listed three results. What are these?
Let's use the file command to get some information.
machine:~$ file myfile.txt
myfile.txt: ASCII text
|
|
This shows us that myfile.txt is a simple (ASCII) text file.
What about the others?
machine:~$ file mydirectory
mydirectory: directory
file mydata.zip
mydata.zip: Zip archive data, at least v2.0 to extract
|
|
This tells us mydirectory is actually a directory
and that mydata.zip is a zip archive. It even
includes the zip software version number required to extract it.
3. View A Text File
Let's look at the contents of the myfile.txt file.
machine:~$ cat myfile.txt
This is a test file
|
|
Using cat we print the file to our terminal screen.
It only contains the text "This is a test file".
4. Removing Files
The myfile.txt file is not really useful, let's remove it.
The rm command is used to remove files, let's make sure
it is no longer there using ls to list our files.
machine:~$ ls -1
mydata.zip
mydirectory/
|
|
Only two results this time, it was removed.
5. Copy A File
The mydata.zip archive is important, so let's
make a backup copy using the cp Linux command.
machine:~$ cp mydata.zip mydata.zip.bak
machine:~$ ls -1
mydata.zip
mydata.zip.bak
mydirectory/
|
|
We copied it and used ls to verify it worked. It did.
6. Renaming Files
Let give mydata.zip.bak a .backup extension
instead.
machine:~$ mv mydata.zip.bak mydata.zip.backup
machine:~$ ls -1
mydata.zip
mydata.zip.backup
mydirectory/
|
|
The mv Linux command was used to move our file
mydata.zip.bak to mydata.zip.backup,
hence renaming it. Once again, ls was used to verify success.
7. Remove A File
Now that we have a proper backup, let's remove mydata.zip.
This is done using the rm command.
machine:~$ rm mydata.zip
machine:~$ ls -1
mydata.zip.backup
mydirectory/
|
|
Note that removed files can not be recovered. Only delete
them when you are sure what they are and you no longer need
them.