Monday, January 28, 2013

Potential errors in aliases

Aliases are very useful for frequently used commands.
If you use Linux and don't know what aliases are, you really should find out.
Here's a very simple tutorial.

Here's one I use in Raspbian on my RPi:

alias update="sudo apt-get update && sudo apt-get dist-upgrade && sudo rpi-update"
Having put this in my ~/.bashrc file (and rebooted), now instead of having to type
 sudo apt-get update && sudo apt-get dist-upgrade && sudo rpi-update
to get a full update (including firmware) of my Raspbian, I just have to type one word

Recently, I was running out of space on the 4GB SDCard I use for my RPi wifi radio, so I created two aliases that would help me locate the largest files and directories on my card.
They were:

alias ducks="du -cs * | sort -rn | head -11" 
alias bigfiles="find . -type f -printf \"%s %p\n\" | sort -nr | head -10"
Now as my RPi radio runs headless, I have to ssh into it to do anything.
Under these conditions, neither of these two aliases worked.
What was wrong?

First, to get aliases to work over ssh you must tell your client computer (or tablet) where to find the aliases.
So, in the server, add the following to ~/.bashrc
source $HOME/.bashrc
assuming your aliases are in ~/.bashrc
(note that the last post in the above link is in error -- there's no equal sign in what's added to ~/.bashrc
You could also issue this command, before running the ssh command)

It's also recommended to add this line to ~/.bashrc

shopt -s expand_aliases
but this was unnecessary in my case.

Now, one alias worked (ducks), but the second one still didn't.
Well, that's strange.

Let's look at that second alias again
alias bigfiles="find . -type f -printf "%s %p\n" | sort -nr | head -10"
OK, I see the problem. We have the string "%s %p\n" in quotes embedded in the alias which is delimited with quotes.
So, the alias doesn't know where it is supposed to end.
Read more about the use of characters in aliases that may have special meanings here.
To remove this ambiguity, just prefix the offending characters with a backslash.
So, this version of the alias works fine:
 alias bigfiles="find . -type f -printf \"%s %p\n\" | sort -nr | head -10"

No comments:

Post a Comment