3

I have the following folder structure:

  alpha
    src
       doit.py
   beta
    src
       doit.py
   gama
    src
       doit.py

and the command

python ../../doit.py --clean --add_source inner

I want to create an alias, doit that executes the corresponding file depending in which parent folder I'm located.

For example:

  1. If I'm inside alpha or one of is sub-directories, when I use:

    doit --addsource extra

to actually run:

python /home/alpha/src/doit.py --clean --addsource extra

  1. If I'm inside beta or one of is sub-directories, when I use:

    doit --addsource inner

to actually run:

python /home/beta/src/doit.py --clean --addsource  inner
1
  • 1
    This feature (directory specific local aliases) has originally been invented in 1980 on UNOS, the first UNIX clone. Since 8 years, it is available in the maintained version of the Bourne Shell - see schilytools. – schily May 2 '20 at 13:53
6

You would be better served by a shell function:

doit () {
    local dir

    case $PWD/ in
        /home/alpha/*) dir=alpha ;;
        /home/beta/*)  dir=beta  ;;
        /home/gamma/*) dir=gamma ;;
        *) echo 'Not standing in the correct directory' >&2
           return 1
    esac

    python "/home/$dir/src/doit.py" --clean "$@"
}

This would set the variable dir to the string alpha, beta or gamma depending on the current working directory, or complain that you're in the wrong directory tree if the current directory is elsewhere.

It then runs the Python script, utilizing the $dir value, with the --clean option and adds whatever other arguments that you've passed to the function.

You would add this shell function's definition to wherever you ordinarily add aliases.

2
  • I wonder if there's an argument to make for returning 127 from the case statement, to help distinguish between a failure to run the script and a failure of the script itself. – chepner May 2 '20 at 21:59
  • @chepner There's an argument for that, but rather than failing to execute a command, we're detecting that the user is located in a invalid directory. I dunno, it's probably not too important. – Kusalananda May 2 '20 at 22:19
1

You can simply use it like below:

alias doit='doit=$(pwd)/src/doit.py;$doit --clean'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.