diff --git a/README.md b/README.md index 0890b62..d09e20c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1602 TILs and counting..._ +_1603 TILs and counting..._ See some of the other learning resources I work on: - [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators) @@ -1896,6 +1896,7 @@ If you've learned something here, support my efforts writing daily TILs by - [A Better Way To Reload ZSH Configuration](zsh/a-better-way-to-reload-zsh-configuration.md) - [Add To The Path Via Path Array](zsh/add-to-the-path-via-path-array.md) +- [Create And Jump Into A Directory](zsh/create-and-jump-into-a-directory.md) - [Link A Scalar To An Array](zsh/link-a-scalar-to-an-array.md) - [Use A Space To Exclude Command From History](zsh/use-a-space-to-exclude-command-from-history.md) diff --git a/zsh/create-and-jump-into-a-directory.md b/zsh/create-and-jump-into-a-directory.md new file mode 100644 index 0000000..229c238 --- /dev/null +++ b/zsh/create-and-jump-into-a-directory.md @@ -0,0 +1,64 @@ +# Create And Jump Into A Directory + +[Oh My Zsh](https://github.com/ohmyzsh/ohmyzsh) defines a function `take` that +we can use to both create and `cd` into a directory. If the directory already +exists, it will simply `cd` into that directory. + +```bash +~/code +❯ take take-demo + +~/code/take-demo +❯ mkdir already-exists + +~/code/take-demo +❯ take already-exists + +~/code/take-demo/already-exists +❯ cd .. + +~/code/take-demo +❯ take one/two/three + +~/code/take-demo/one/two/three +❯ +``` + +First `take` creates and `cd`s into `take-demo`. Then `take` only `cd`s into +`already-exists`. Then we see that `take` can create multiple levels of nested +directories. + +With the help of `which` we can see how `take` is defined: + +```bash +$ which take +take () { + if [[ $1 =~ ^(https?|ftp).*\.tar\.(gz|bz2|xz)$ ]] + then + takeurl "$1" + elif [[ $1 =~ ^([A-Za-z0-9]\+@|https?|git|ssh|ftps?|rsync).*\.git/?$ ]] + then + takegit "$1" + else + takedir "$@" + fi +} +``` + +We're not dealing with compressed files or git URLs, so we fall through to the +`else` block with invokes `takedir`. + +```bash +$ which takedir +takedir () { + mkdir -p $@ && cd ${@:$#} +} +``` + +The `mkdir -p $@` is what allows it make new, nested directories and then we +`cd` to it. The `${@:$#}` is a way of [grabbing the last argument to the +function](https://stackoverflow.com/a/37601842/535590). This suggests that you +can pass multiple things to `take`, it will create all of them, and then `cd` +you into the last one. + +[source](https://github.com/ohmyzsh/ohmyzsh/blob/master/lib/functions.zsh#L75-L85)