Speed up the work by shell scripts II

In addition to the shell scripts mentioned in this post I wrote another small script:

#!/bin/bash
# texcd - change into the directory
#   corresponding to a certain tex related file
if [ $# -eq 0 ]; then
  echo 1>&2 Usage:    . texcd filename [pattern]
  echo 1>&2 examples: . texcd beamer.cls
  exit 1
fi
cd `kpsewhich $1 | sed 's/(.*)/.*$/1/'`
echo Changed to: `pwd`

It’s purpose is to change into the directory where a certain tex related file resides. For instance if you want to search through some beamer class theme files, you don’t have to know the directory, just type
. texcd beamer.cls
and you will enter (for instance) the directory /usr/share/texmf/tex/latex/beamer/base/. The dot at the beginning of the command is important. Thats one reason why I show this small script too. Normally if you change the directory inside a script, after the script is finished you will be back inside the directory where you were before, because the script starts a new shell for itself. If you want to run the commands inside your current shell you can use the source command, the dot I’ve used is just an abbreviation for source.

Some additional hints I didn’t mention in the other post: instead of putting the scripts into your home directory you could copy them into your local file system, for instance:
sudo cp texcd /usr/local/bin/
and those scripts should be made executable using chmod:
chmod a+x /usr/local/bin/texcd
Thats recommendable for the other scripts too.

15. July 2008 by stefan
Categories: Tools for LaTeX | 2 comments

Comments (2)

  1. A better way is using a shell function instead of a script:

    function texcd ()
    {
    cd $(dirname "$(kpsewhich "$1")");
    }

    Adding this to ~/.profile allows you to write

    texcd beamer.cls

    at the command line. Error handling is left as exercise to the reader.

  2. Hi Michael,

    thank you for your constructive comment. This shell function is working fine with bash. I would rather put this function into ~/.bashrc instead of ~/.profile, because ~/.profile may be executed by other shells like sh. sh stops with Syntax error: “(” unexpected, that may even prevent login to an X session, except in safe mode.
    Btw. I added code-Tags to your comment to improve readability, else the quotation marks might cause a problem if a reader tries copy&paste.

Leave a Reply to Stefan Kottwitz Cancel reply

Required fields are marked *