Assignment 2
From terminal
1) Open any empty text file and write on it.
Reading file
2) Display its content. (at once)
3) Display its content line by line (using loop)
#!/bin/bash
# Read file line-by-line
while read line; do
echo "$line"
done < "input.txt"
4) head/tail - Read first or last N lines of a file. Useful for previewing file contents:
head -n 10 file.txt
tail -n 5 file.txt
5) Reading CSV file
# Read CSV file line-by-line
while IFS="," read -r col1 col2 col3; do
echo "$col1 | $col2 | $col3"
done < file.csv
Writing to files
1) cp - Copy files and directories
cp file.txt file_copy.txt
2) find - Search for files recursively matching given criteria. Helps locate files based on name,
size, permissions, etc:
find /home -name "*.txt"
3) To write to a file, use the >
#!/bin/bash
# Write output to file
echo "This is some text" > outfile.txt
4) This writes "This is some text" into outfile.txt, overwriting any existing content.
To append instead of overwrite, use >>
#!/bin/bash
# Append output to the end of file
echo "Appending this line" >> appendfile.txt
Renaming and Deleting Files
You can rename or delete files and directories from within scripts.
To rename a file:
#!/bin/bash
# Rename file
mv oldname.txt newname.txt
To delete:
#!/bin/bash
# Delete file
rm filename.txt
And to remove a directory and all its contents recursively:
#!/bin/bash
# Delete directory recursively
rm -r directoryname
File exit or not in the location
#!/bin/bash
filename="test_file.txt"
if [ -e/-d "$filename" ]; then
echo "$filename exists"
else
echo "$filename does not exist"
fi
The -f flag for the if condition checks if the file exists and is a regular file. Other test flags
include:
-d - Directory exists
-e - File exists (regular file or directory)
-s - File exists and size is greater than 0
Getting File Metadata
You can get useful metadata about files like size, permissions, etc.
For example, get a file's size in bytes:
#!/bin/bash
# Get file size
filesize=$(stat -c%s "file.txt")
echo "Size: $filesize bytes"