./ahmedhashim

One-liners: u

Deep inside a repo, getting back out means typing cd ../../../.. and counting the dots. I do it often enough that it warranted a function in my ~/.zshrc:

u() { cd $(printf '../%.0s' {1..${1:-1}}); }

u goes up one directory. u 3 goes up three.

Breaking it down

The argument gets a default:

${1:-1}

This is the first positional parameter, falling back to 1 when there isn’t one. It’s what lets a bare u mean “up one”.

The brace expansion does the counting:

{1..${1:-1}}

With u 3, the range becomes {1..3}, which expands to three words: 1 2 3. The numbers themselves are throwaway; they only exist to be counted.

This is also the zsh-only part. Zsh runs brace expansion after parameter expansion, so a variable inside a range works. Bash does it in the other order: the braces never expand and printf gets the single literal word {1..3}. The function still runs, it just climbs exactly one level no matter what you pass it. Porting this to bash means reaching for seq instead.

The trick is printing nothing, repeatedly:

printf '../%.0s' 1 2 3

printf reuses its format string until it runs out of arguments. %.0s consumes an argument and prints at most zero characters of it, so each one leaves behind a single ../. Three arguments make ../../../.

Wrap that in cd $(...) and that’s the whole function.

One quirk: u 0 goes up two levels, because zsh expands {1..0} as a descending range into 1 0. I’ve never once wanted to cd zero directories up, so it stays unguarded.

If I overshoot, cd - puts me right back.