File Handling

File handling is a core part of Linux scripting: creating, copying, moving, syncing, compressing, comparing, finding and validating files safely.

Core Commands

CommandWhat it doesExample
touchCreate empty filetouch app.log
mkdir -pCreate nested directoriesmkdir -p /opt/apps/config
cpCopy filescp app.jar /opt/apps/
cp -rCopy directoriescp -r config/ backup/
mvMove or renamemv old.log archive.log
rmRemove filerm temp.txt
rm -rfRemove recursivelyrm -rf temp/
findFind by name/type/sizefind /var/log -name '*.log'
tarArchive and compresstar -czvf backup.tar.gz app/
zip/unzipZip archive managementzip -r app.zip app/
rsyncFast sync and copyrsync -avz logs/ user@host:/backup/
diffCompare text filesdiff a.yml b.yml
statShow metadatastat app.jar
md5sumVerify checksummd5sum app.jar

Safe Patterns

cp -v source target
mv -v old new
rm -i important.txt
rsync -avzn source/ target/   # dry run first
find . -type f -name '*.log' -mtime +7 -delete

Useful Checks

du -sh *
find . -type f | wc -l
find /data -type f -size +500M
ls -ltr
file app.jar