Search code examples
bashmsys

How to cd to directories linked in .lnk files?


In msys bash in Windows, I'd like to cd to the directory a (Windows native) .lnk links to. These are the standard Windows shortcuts. I want to be able to do this:

~ $ cdlnk programs.lnk
/c/Program\ Files/ $

I've come this far:

strings "$lnk" | grep -A 1 DATA | tail -n 1

gives me the path the shortcut links to. However, now I'm stuck. I can either

  1. Make an alias in .bashrc - but then I cannot use pipes or pass the parameter to a script, i.e. I cannot run above code.
  2. Make a script cdlnk.sh - but then I can only change its cd and not that of the calling shell.

Solution

  • To both be able to process parameters and modify the current shell, you can use a shell function in a file that has to be sourced, for example .bashrc.

    For the command you have, the function might look like this:

    cdlnk() {
        strings "$1" | grep -A 1 DATA | tail -n 1
    }
    

    You could make this a little shorter by using sed instead of grep and tail:

    cdlnk() {
        strings "$1" | sed -n '/DATA/{n;p;q;}'
    }
    

    where -n suppresses output, and on a line matching DATA, the commands are n (get next line into pattern buffer), p (print the line), and q (exit – no need to look at the rest of the file).