Create Files
You can create files in Bash using the touch
command or redirection operators. The touch
command creates an empty file if it doesn’t already exist:
touch filename.txt
Alternatively, you can use the redirection operator to create a file and write to it:
echo "Hello, World!" > filename.txt
Read Files
To read the contents of a file, you can use the cat
, less
, or more
commands. The cat
command displays the entire file content:
cat filename.txt
For larger files, less
and more
allow you to scroll through the content:
less filename.txt
Write to Files
You can write to files using redirection operators. The >
operator overwrites the file, while the >>
operator appends to it:
echo "New content" > filename.txt # Overwrites the file
echo "Additional content" >> filename.txt # Appends to the file
Copy Files
To copy files, use the cp
command:
cp source.txt destination.txt
Move and Rename Files
The mv
command is used to move or rename files:
mv oldname.txt newname.txt # Renames the file
mv filename.txt /path/to/directory/ # Moves the file
Delete Files
To delete files, use the rm
command:
rm filename.txt
Checke File Existence
Before performing operations on files, it’s often useful to check if they exist. You can use conditional statements for this:
if [ -f filename.txt ]; then
echo "File exists."
else
echo "File does not exist."
fi
You can view other useful examples at the following links:
CyberWorld | Files Operation: touch, cat, less – read content of files (optimusing.dyndns.org)