Archive for the ‘unix’ Category
Start a web server from your pwd using Ruby and Thin
Occasionally I’m interested in grabbing files from a directory on a remote host. This could be for another process to consume or to look at on my local work station.
The standard way of doing this is using scp, ftp or a file share. I prefer to start a short-lived web server that shares the file system.
To make this simple I use a ruby script to allow me to start a webserver from the directory I’m currently in.
['rubygems', 'thin', 'rack', 'socket'].each {|file| require file }
Thin::Server.start(IPSocket.getaddress(Socket.gethostname), 7777) do
use Rack::CommonLogger
run Rack::Directory.new(Dir.pwd)
end
As an alias for ~/.bashrc it looks like this:
alias rshare="ruby -rubygems -e \"['thin', 'rack', 'socket'].each {|file| require file };"\
" Thin::Server.start(IPSocket.getaddress(Socket.gethostname), 7777) {"\
" use Rack::CommonLogger; run Rack::Directory.new(Dir.pwd) }\""
This allows you to go to port 7777 on the host and retrieve the files you’re interested in.
@joejag /tmp $ rshare >> Thin web server (v1.2.7 codename No Hup) >> Maximum connections set to 1024 >> Listening on 10.0.0.2:7777, CTRL+C to stop 10.0.0.8 - - [01/Mar/2011 07:45:15] "GET / HTTP/1.1" 200 2153 0.0038
You will need to have the ‘thin’ and ‘rack’ gems installed to do this.
Automatically resolving jars for the Java classpath
When you use the Java classpath (pre java 1.6) you have to manually list each jar on your classpath such as:
java -cp lib/database.jar:lib/commons.jar:/lib/log.jar com.joejag.Main
On Java 1.6 a little known feature is that you can now use wildcards, so the above command becomes:
java -cp lib/*.jar com.joejag.Main
I still have to use an earlier version of Java for some applications I handle. To save having to list all the jars manually I use the following bash script which allows you to automatically list all the jars in a directory:
java -cp `find lib -name *.jar -exec printf :{} ';'` com.joejag.Main
Using Ruby as an AWK replacement
Someone at work asked if you could use Ruby like AWK. I did a little digging and found that you can.
cat file | ruby -n -a -e 'puts "#{$F[0] $F[1]}"'
‘-n’ makes the Ruby iterate over all lines successively assigning them to $_
‘-a’ makes Ruby split $_ into its parts assigning the result to $F which is an array of strings
‘-e’ means that what follows is code to be executed.
‘-F’ specifies the column separator
I performed a speed comparison on some different size files and operations. For files under 500kb lines Ruby has comparable performance to AWK. For anything larger then Ruby (1.8.6) is at best twice as slow. Though I wouldn’t expect a general purpose language to outperform a specialist tool.