Useful Linux scripts etc.

A better find

I keep using the find command in Unix as such: “find / -name SOMETHING” (Yes, I know there’s locate, too). You always get an error message when you hit a directory you don’t have permissions for, but I usually don’t care about those directories anyway, so it makes sense to pipe those error messages that appear on stderr to /dev/null. This works like this:

find / -name SOMETHING 2> /dev/null

Display progress when using DD

dd if=INFILE of=OUTFILE bs=4M status=progress

Rescuing delete files in Linux

It happens. You delete a file, but not to the recycle bin, and need it back – BAD. This happened to me for a source file. Here’s what to do (based on this).
Drop to the Linux command line. If you’re on a graphical user interface press CTRL+ALT+F3 and you should be on terminal tty3. Log in like you usually would. Keep in mind you’ll need root privileges later on…
Tell all users you’re going to single user mode:

wall

Wait a bit and press CTRL+D to put in a command. Go to single user mode to prevent stuff being written to disk:

init 1

Use grep to recover your file:

grep -i -a -B20 -A100 'some text from the file' /dev/sda1 > dump.txt

The grep commands are:
-i : Ignore case distinctions in both the PATTERN and the input files i.e. match both uppercase and lowercase character.
-a : Process a binary file as if it were text
-B Print number lines/size of leading context before matching lines.
-A: Print number lines/size of trailing context after matching lines.

If you now have a file too big to edit, try copying only a few lines to another file:

head -100 dump.txt > 100lines.txt

Find the device name of your WiFi adapter

iwconfig | grep --color=never "IEEE 802" | sed "s/^\W(\w+)\b./\1/"

Recursively find files with extension and pipe to program

This command searches (all *.h/.hpp/.hxx/.c/.cpp/.cxx files) recursively in the current directory and pipes all files to clang-format as a file list in one command. It also excludes the “build” directory (I use CMake), but you can just omit the “grep” step to remove that.

shopt -s globstar extglob failglob && ls **/*.@(h|hpp|hxx|c|cpp|cxx) | grep -v build | tr '\n' ' ' | xargs clang-format -i

Print the return code of a shell command

echo $?

You can find some other Linux stuff here.

Published by HorstBaerbel

Software developer by trade and interest, but I venture into the electronics- and diy-world from time to time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website at WordPress.com
Get started
%d bloggers like this: