📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

Make file empty with bash script

Need to clear out a file and start fresh? No problem! I've got a handy little bash script that can empty out a file for you using a few different methods. Check it out:

#!/bin/bash

# First, let's set the path to the file you want to zap
FILE_PATH="/path/to/your/file.txt"

# Now, take your pick from these empty file techniques:

# Method 1: The old redirect trick
# Just feed an empty string into the file, overwriting everything
: > "$FILE_PATH"

# Method 2: Truncate to size zero (uncomment to use)
# truncate -s 0 "$FILE_PATH"

# Method 3: Echo an empty string (uncomment to use)  
# echo -n > "$FILE_PATH"

# Method 4: Copy nothing from /dev/null (uncomment to use)
# cp /dev/null "$FILE_PATH"

# Method 5: Get the big gun - dd (uncomment to use)
# dd if=/dev/null of="$FILE_PATH"

echo "Voila! $FILE_PATH is now empty as a whistle."

So there you have it - five different ways to turn that file into a clean slate. Just uncomment the method you want to use by removing the # at the start of the line.

The redirect trick is probably the simplest and most common approach. But if you're feeling fancy, give truncate or one of the other methods a shot. They all get the job done in their own unique way.

Don't forget to swap out that /path/to/your/file.txt for the actual path to your file, and you're all set! Let me know if you need any other file emptying tricks up my sleeve.