Search code examples
pythontcsh

Alias tcsh to python script then return result back to tcsh?


I want to create a version of cd which will strip off a filename from a directory structure and then cd to that directory.

So for example if I put in the (tc)shell

cd /net/homes/me/myfile.jpg 

it will strip off 'myfile.jpg' and cd to the directory structure. I tried this is my .cshrc:-

alias ccd '/net/homes/me/scripts/getDir.py'

Then my getDir.py file reads as:-

#! /usr/bin/python

import sys
import os

def get_dir():
    the_dir = sys.argv[1]
    dir_split = the_dir.split("/")
    dir_count = len(the_dir.split("/"))

    file_count = len(dir_split[dir_count-1])
    only_dirs = the_dir[:-file_count]
    #print only_dirs
    os.chdir(only_dirs)


get_dir()

This strips off the filename part of the dir structure fine (I can tell that from the print statement) but the chdir command doesn't seem to work.

Thanks!


Solution

  • There's a standard binary called dirname which does this for you, so you can just use...

    alias ccd 'cd `dirname \!:1`'
    

    This works, can you explain the syntax?

    Well, the dirname \!:1 part means to run the dirname program with the first argument passed to the aliased command, and the backticks substitute the output from that program into the cd command.