Saturday, 27 October 2007

Geeky experiments with bash functions

return doesn't mean what you think it does

Modern UNIX shells like bash have the ability to define functions. Functions are a great way to factorise parts of code that you need to use in several areas of your script or isolate discrete pieces of logic. In most programming languages, one fundamental aspect of functions is that they can return a value which is the result of whatever computation they were doing. And indeed a shell like bash has a built in return command. But, hang on, if you read up on return, you realise that it can only return integer values. The reason for this is that return works the same way as exit: it sets the $? variable with the value given as argument, or 0 if no argument is given, and aborts the function. exit aborts the whole script instead. So, if you use return, use it to provide the calling code with an error code. This doesn't solve the original problem though: how can we return a value from a function, such as a character string?

As often with UNIX, the answer is deceptively simple and consistent with everything you know about scripts: just echo the value you want to return and call your function as if it was a full blown script, with inverted quotes or the $(...) construct, as in the example below.

#!/bin/bash

function f {
  echo "[ $1 ]"
  return 1
}

s=`f "abc"`
echo "\$?=$?"
echo "\$s=$s"

Save this in a file called fn.sh, make it executable and run it:

$ ./fn.sh
$?=1
$s=[ abc ]

As you can see, the $? special variable was set with the value 1 and the $s variable was updated with the result of the function.

Recursive fun

Once you know how to return a value from your function, the next thing you need is to know how to pass it some parameters. Once again, it works exactly the same as in a full blown script: you just use the $n positional variables. Recursion works as you expect as well. So let's demonstrate with a classic textbook example: a recursive factorial.

#!/bin/bash

function fact {
  if [ $# -lt 1 ]; then
    return 1
  elif [ $1 -lt 1 ]; then
    return 2
  elif [ $1 -eq 1 ]; then
    r=1
  else
    r=$(( $1 * `fact $(( $1 - 1 ))` ))
  fi
  echo "$r"
}

fact $1

Save it, run it and you should get something like the following. Don't give it too high a value though, we'll see why in a second: 10 should be enough to demonstrate that it works.

$ ./fact.sh 10
3628800

While we're here, let's have a quick look at this function as it has a couple of interesting constructs. It does the following:

  • check the number of parameters it has been passed, using the $# variable, and returns an error if less than 1,
  • check that the first parameter is positive, as a negative value is invalid and return an error code in this case,
  • check the termination condition of the recursion and set the result if we have reached that condition,
  • finally calculate the factorial by calling itself recursively.

Note the use of the $((...)) construct to do the relevant arithmetic calculations: one is needed inside the recursive call to the function, to tell ensure the value passed is the result if $1 - 1 rather than the three parameters $1, - and 1; another one is needed outside the call to calculate the product.

This script also proves that when using functions in this way, the variables defined inside the function are local and not overwritten by a subsequent call. This is because the use of the back quotes actually forks a new process in which the function is called. You can verify this by adding a sleep statement inside the function, running the script in the background and running ps:

$ ps
  PID  TT  STAT      TIME COMMAND
  394  p1  S      0:00.07 -bash
 2414  p1  S      0:00.01 /bin/bash ./fact.sh 10
 2415  p1  S      0:00.00 /bin/bash ./fact.sh 10
 2416  p1  S      0:00.00 /bin/bash ./fact.sh 10
 2417  p1  S      0:00.00 /bin/bash ./fact.sh 10
 2418  p1  S      0:00.00 /bin/bash ./fact.sh 10
 2419  p1  S      0:00.00 /bin/bash ./fact.sh 10
 2420  p1  S      0:00.00 /bin/bash ./fact.sh 10
 2421  p1  S      0:00.00 /bin/bash ./fact.sh 10
 2422  p1  S      0:00.00 /bin/bash ./fact.sh 10
 2423  p1  S      0:00.00 /bin/bash ./fact.sh 10
 2424  p1  S      0:00.00 sleep 5

Each child process has its own context and variables and doesn't interfere with the other ones. However, this means that you have to be extremely careful when using functions this way as you could quite easily spawn a large number of processes. Recursion in particular could be deadly.

Pipe dreams

Finally, if a function generally works like a script, can we pipe it? yes but if you want it to be on the consuming side of the pipe, you will need to adapt the function to take its input from stdin rather than a parameter. And you can even make it work so that it can do both. Here is a modified version of the very first script:

#!/bin/bash

function f {
  if [ $# -ge 1 ]; then
    echo "[ $1 ]"
  else
    while read line; do
      if [ -n "$line" ]; then
        echo `f "$line"`
      fi
    done
  fi
}

find ~ -type f -print | f

You could apply this construct to most functions: check if there are any parameters, in which case you can use them normally, otherwise read each input line and call the function recursively using the line as parameter. Don't forget to enclose it between quotes though, so that it is passed as a single parameter and blank lines don't trigger an infinite recursion. Run this script and you should get a list of all files in your home directory, with each file enclosed in square brackets.

That's it for functions. Please tell me if any of the examples above don't work for you. I have tested them on Ubuntu Linux, Sun Solaris Express and Mac OS-X so they should be fairly portable but you never know. They may not work with shells other than bash but feel free to experiment.

Tuesday, 16 October 2007

British Gas Customer Service

Unusually, I was home early tonight. I got a knock on my door so I went and opened.

Hello, I am from British Gas, can I ask you a few questions?

Yes, sure.

Can I ask you why you cancelled your electricity contract with British Gas?

I never had electricity through British Gas, I only buy gas from you.

Ah... So you never had electricity supplied by us? And you would not be interested in buying electricity from us, in addition to gas?

No.

Why not? We have good prices, you could save a lot of money.

I am happy with my current supplier.

Ah... OK, thank you, good night!

So now British Gas know that I only buy gas and not electricity from them. That's progress. It's only taken them 6 years to realise.

Monday, 15 October 2007

Labour Party's Reading Skills

I just got a call from a member of the Labour Party. I suppose they got my details from the Electoral Register. If so, said register clearly specifies that I am a French citizen. Therefore, asking me what party I was planning to vote for at the next General Election was quite senseless as I cannot vote for General Elections. Someone should teach the members of the Labour Party (and the others) basic skills like reading, that would save them quite a few phone calls.

Monday, 24 September 2007

The Big 18-Month Mobile Contract Scam

If you buy a new mobile phone contract in the UK these days, chances are that the sales person you are going to talk to will try to sell you an 18 month contract rather than a 12 month one. Be extremely careful before you decide to take such a contract. Perks will include a free mobile phone and a slightly cheaper contract than the shorter one. The downside is that you can only upgrade your handset after 18 months rather than 12. Not a major problem you may think if you are not the type who needs the latest handset as soon as it comes out.

Think again. And ask the sales person what is the length of the manufacturer's warranty on the handset. Chances are, the warranty for the handset is 12 months. If your handset starts malfunctioning through no fault of your own while it is under warranty, or once you are eligible for an upgrade, the provider will replace it at no cost to you. However, if your handset plays up after the warranty has expired but before you are eligible for an upgrade, that is during the last 6 months of a typical 18 month contract, then the provider will not replace the handset and you will have to buy one yourself at full market price.

Of course all this is explained in the small print of your contract but no sales person will mention it to you without prompting. So don't forget to ask and if the warranty on the handset expires before you are eligible for an upgrade, don't take the contract.

I just got bitten by that interesting loophole with Vodafone and am now left with a malfunctioning handset for the last 3 months of my contract. Luckily the fault is not debilitating, it just means that the handset occasionally restarts while in the middle of a call, cutting the call short. Not a complete failure then, but still extremely annoying. Evidently, the second my current contract expires, I will go shopping around for a new contract and I will only stay with my current provider if they can offer me a significantly better deal than the competition.

As Vodafone's support told me, everybody else does the same because the handset's warranty is set by the manufacturer, not the network and they have no say in this. Well, maybe they should talk to the manufacturers and solve this loophole. The reason why it should be solved is because the handset is bundled with the contract. You don't buy the handset, you buy a contract to provide you with mobile phone services and you are given a handset as part of that contract to enable you to connect to the service. The cost of the handset is then included in the price you pay for the service and it should be completely covered by the service agreement for the duration of that agreement. In the case where you buy the handset separately, you buy a service and an electronic device to use with this service, there are two separate transactions and it is therefore sensible to treat them separately. Not when the handset is bundled with the service.

I may be barking at the wrong tree but I will definitely contact the Office of Fair Trading and ask them whether this practice is actually fair. I shall update this blog when I have an answer.

Sunday, 23 September 2007

Bad Interface Design

Apple Computers are reknown for some of the best user interfaces. Like everybody else, they can occasionally get it wrong. I just had an amusing example of this. If you go to the HSBC web site and download any of their PDF documents such as their terms and conditions, you will notice that there is a slight bug that adds ;jsessionid= followed by a lot of gobbledygook at the end of the file name, after the extension, thus producing a file with an unusually long extension that OS-X doesn't recognise. So the first thing you'd want to do is change that file name and remove all the jsessionid malarkey at the end of the file name. When you do that, OS-X thinks you want to change the extension and are in risk of ending up with a file name it can't handle automatically. So it warns you and asks if you really want to do this, assuming you don't, as shown below:

Error dialogue with inaccessible button

Error dialogue with inaccessible button

In this example, you can just about see the other button pushed all the way left and therefore click on it as you really, really want to change that extension. But if you had just one more letter or if you changed the j in the ID for an M, the right button would be that little bit much wider and the left button would completely disappear. As you can't change the dialogue window's size, you're stuffed and you have no choice but to click on the highlighted button and leave your file name as is. The only way I found around this is to open the terminal and use the command line to change the name. That's one thing that OS-X has going for it: as it's UNIX underneath, you can always bypass the user interface when it gets in the way. On the other hand, that's not something that is very accessible to the average user.

There are a couple of solutions that Apple could apply to their dialogue boxes when such a problem occurs:

  • make the dialogue window's resizable and/or scrollable;
  • extend the window accordingly, although you'd get the same problem if you got to stupid extension lengths as long as the width of the screen;
  • make the buttons stack up and extend the window vertically.

The moral of the story is: when designing user interfaces, test them with very stupid values that make it break. Someone is bound to use such values one day or another, if only by accident.

Saturday, 22 September 2007

Big Brother Sam

Wired News have an interesting article about screening at American airports and the type of information they collect. This strengthens my resolution not to fly to the United States until further notice. Not that I have anything to fear from such screening but I really think this is going too far. It looks like Uncle Sam is more and more turning into Big Brother Sam!

Tuesday, 18 September 2007

Word of the Day

Dictionary.com's word of the day is potboiler. No, I didn't know it either. There you go, you learn something new every day.

Wednesday, 22 August 2007

Cheap Taxi

I arrived in Sofia yesterday morning. The first thing I needed to do was find a hotel. James, whom I had met on the train already had one booked so we decided to go to his hotel and drop the bags there. If they had an extra room free for me, that'd be ideal, otherwise I'd go looking but without having to lug the bags around.

The first thing we did was have a coffee and pull out the map I had bought in Belgrade to have an idea where his hotel was. We found it easily right in the centre and estimated it was about 2 kilometres from the train station. That was easily walkable but we decided we really didn't want to carry the bags and we'd take a taxi. So once the coffee paid for, we went to the taxi rank.

As soon as we got to the taxi rank, we were approached by a guy who asked if we wanted a cheap taxi. Smelling a trap we asked how much it would be to the address we wanted to go to. He immediately answered 10 Euro, pulling his it's-very-far-away-you-know face. Even in London, they wouldn't attempt to charge you that much for a distance you could walk! We thanked him and went to an official taxi. We were in front of the hotel some 10 minutes later and got charged 4 Leva: 2 Euro.

Moral of the story: unlicensed taxi drivers have an interesting understanding of the word cheap.

Linguistic Gymnastics

If you ever want to learn Serbian, the good news is that it is a phonetic language: if you can read it, you can speak it and vice versa. The bad news is that is can be written using either the Latin or the Cyrillic alphabet so you may see signs in both scripts. For instance, Thank you can be written Hvala or Хвала. It can get very confusing when you have a map that uses the Latin alphabet but the street signs are all in Cyrillic. Then the even worse news is that Serbian extends both alphabets with extra letters that don't exist in the standard versions of either, such as Đ in the Latin script or Љ in the Cyrillic one. And then comes the practical question: what dictionary order is used? The Latin and Cyrillic alphabets have different dictionary orders so does it mean that when you buy a dictionary, the order the words are in depends on the alphabet it is published in? I'm not sure I want to know the answer.

Monday, 20 August 2007

Impossible Connection

Sometimes you meet someone in the weirdest of situations and realise that you have the most unexpected of connections. Last night at the Belgrade Beer Fest, I met a couple of Serbian guys when we started discussing the blueberry flavoured beer I had just bought. Of course, they eventually asked me where I came from. When I said France, one of them asked me to be more precise. So I said I came from Brest, fully expecting to have to explain where it was. To my surprise, he said that he had been there. But the most surprising is the reason he went there: he just loved the poem Barbara from Jacques Prévert and wanted to see the town the poem was about so one day he was in France visiting family, he went all the way to Brest. How cool is that?