Skip to content

Instantly share code, notes, and snippets.

@jimfinnis
Last active December 6, 2022 16:21
Show Gist options
  • Save jimfinnis/e2eb778a23a4c8eb6f6586d1aa956303 to your computer and use it in GitHub Desktop.
Save jimfinnis/e2eb778a23a4c8eb6f6586d1aa956303 to your computer and use it in GitHub Desktop.
This is the magic behind the shell "up" command. You can do "up 3" to go up 3 levels in the directory hierarchy, or "up foo" to go up to a directory whose name contains "foo".
#!/usr/bin/python3
# Used as part of 'up' to move up complex directory trees:
# With no args, prints '..'
# With a numeric argument, prints '../../' up as many levels as the arg.
# With a string argument, looks for a string in the path, and prints '../'
# enough times to go up to that directory.
#
# You also need to add to your .bash (I use .bash_aliases):
#
# function up(){
# cd $(fup $1);
# }
import os,sys
args = sys.argv
args.pop(0)
if len(args)==0:
s = '..'
else:
arg = args[0]
if arg.isnumeric():
s='../'*int(arg)
else:
p = os.getcwd()
lst = p.split('/')
lst.reverse()
ct=0
for i,x in enumerate(lst):
if arg in x:
ct = i
break
s='../'*ct
print(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment