Unix tricks

Some neat unix tricks

port scanning using the shell

It is easy to port scan using simple unix tools

$ host="some host"
$ port="some port"
$ timeout 3 bash -c "echo >/dev/tcp/$host/$port" && echo open || echo closed

sed in-place replacement with backup

Sed is often used to act on file in-place. It is very convenient to be able on a single command line to also backup the file.

# replace SOMETHING by ELSE in the file
# and create a backup file named bar.txt.bak
$ sed -i.bak 's/SOMETHING/ELSE/g' bar.txt
# remove from the third to the last line of the file
# and create a backup file named bar.txt.bak
$ sed -i.bak '3,$d' bar.txt

remove empty lines in file

Getting rid of empty lines in a file is easy with sed. /^$/ will find lines with nothing between the beginning of the line (^) and the end of it ($) and then d deletes it:

$ sed '/^$/d' <file-path>

insert file in vim

It sometimes happen you want to insert a entire file at the cursor position in vim. This is the command that will do that:

:r <file-path>

remove file with weird names

Sometimes you have files that get created (or you created them by error) that are not that easy to remove without potentially messing things up like for example --, ~, /, ...

The trick is first to retrieve the inode number of that file by listing all files in the directory:

$ ls -i

And then remove the file by its inode number using find:

$ find . -inum <inode-num> -exec rm {} \;

reverse lines in file

You probably know cat, well there's also tac:

$ cat /tmp/foo
Line 1
Line 2
Line 3
$ tac /tmp/foo
Line 3
Line 2
Line 1

get N random lines from a file

randomize-lines is a nice tool allowing to quickly (and easily) randomize lines of a file. After installation, its binary is rl (at least on debian). Combining it with head allows to retrieve N random lines from a file

# retrieveing 100 random lines from foo.txt
$ rl foo.txt | head -100

execute last command as root

I rarely use sudo, but when I need to, I usually forget it. This allows to execute latest command with sudo:

$ sudo !!

get your bandwidth from the cli

The tool speedtest-cli is very useful to retrieve the current download/upload speed.

$ speedtest-cli | grep 'Download\|Upload'
Download: 711.94 Mbit/s
Upload: 264.28 Mbit/s