Unix tricks 2

some more neat unix tricks

Editing binary with vim

Open the binary in vim with

:% !xxd <file-path>

change the needed parts and then save it with:

:% !xxd -r

Ssh escape sequences

You can control some SSH settings when inside an SSH session using the escape sequences: <enter>~

With ? you get a list of available options:

  • when all hope is gone use <enter>~. to close the session
  • when you want to increase/decrease verbosity use <enter>~V/v
  • when you want to put in background use <enter>~&
  • ...

For a list of all options, see ssh's man page under ESCAPE CHARACTERS:

man --pager='less -p ^ESCAPE' ssh

Average over multiple lines

Use awk to sum all lines and get the average of the sum at the end. This is useful for example for a stripped wc command's output.

... | awk '{ sum += $1; n++ } END { if (n > 0) printf "%.f\n",(sum / n); }'

Quick'n'dirty share on LAN

Let's say you want to quickly share something without much fuss, use python SimpleHTTPServer:

SHARE="/tmp/share"; mkdir -p $SHARE; cd $SHARE; python -m SimpleHTTPServer

Then copy what to want to share into $SHARE and simply access it on http://your-ip-here:8000

Add comma to all lines except the last one

Easily append a comma to each line except the last one:

$ cat /tmp/tmp
a
b
c
d
e

use awk to transform each line and wc to calculate the total number of line for the if clause:

$ cat /tmp/tmp | awk -v nlines=`wc -l < /tmp/tmp` '{if (NR == nlines) {print $0} else {print $0","}}'
a,
b,
c,
d,
e

Unix time (epoch)

A nice dmesg switch is -T which translates the unix times of each line into human readable date/time.

Otherwise you could always use the unix tool date to transform epoch to human readable date/time with following command:

date -d @<epoch>

Bash script duration

I often use either time or enclose my process within two date calls to monitor the duration of a script.

One interesting built-in shell variable is SECONDS which will output, each time it is referenced, the number of seconds ellapsed since shell invocation.

This example script

#!/bin/bash
echo $SECONDS
sleep 10
echo $SECONDS

will produce

0
10

see more info on built-in shell variables here