Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

Thursday, June 02, 2011

Writing binary files with bash

Hello,
I'm trying to see if I'm able to write some binary file using bash. So, when writing a binary file you often want to write a number into binary format. I ended up with this simple function for writing numbers in little endian:

function num2bin() {
printf $(printf %.$(($2*2))x\\n $1|
sed 's/\([0-9a-f][0-9a-f]\)/\\x\1/g')|
awk -F '' '{ printf $4$3$2$1 }'
}


The first parameter is the number to write, the second is the number of bytes (up to 4). For example "num2bin 40 4" will output a 4-byte long string containing the number 40 in little endian.

How do we use it? I wrote an example script for creating a wav file with noise (according to wav specifications) that you can read here.

Let me know if you have a simpler version of the num2bin function.

Friday, May 27, 2011

Complete variables with cd command in bash

Hello,
lately I've been searching for a way to complete variables containing directories with the "cd" command in bash. This is very helpful if you have something like "cd $mydir/". This is not actually working in debian bash-completion.
Then I've realized that other commands such as "ls" actually expand variables. I looked for some "complete" combo used for "ls" but not for "cd" in /etc/bash_completion and I came out with the following:

complete -F _longopt -o default cd

Luckily, this is exactly the command needed to enable variable expansion with the "cd" command. Put that in your .bashrc after loading bash_completion and you're done.