5 ms·
cd –, a shell feature I didn't know about
Recently, someone submitted a pull request to one of my projects, which included a shell feature, i always wanted to have, but didn't know it exists. The project includes a little build script, which changes the directory, executes some commands and then changes back to the original directory, where it came from.
To achieve this, i used the "pushd" and "popd" command, which unfortunately seems not to be available on every POSIX platform. So, as an alternative, the pull request included:
cd -
which i never came across and which surprisingly (at least for me) did the same thing... Further research lead me to following information:
"cd -" expands the "-" to $OLDPWD, which, as the name intends, points to the directory visited before. Using this variable results in a history size of 1, so you can only switch between the last and the current directory, but in most cases, that should be enough.
Then I immediately thought of a problem... how to change to a directory named "-"? Well, heres the answer:
cd ./-
Now that I know about it, I use it nearly every day.
Have fun!
- azeirah 8y agoAhh yeah cd - is super useful once you know it. A similar one is !! For example apt install python3 And you forgot sudo, whoops sudo !! !! will be replaced by the last command you executed. Or /etc/logs/apache2/error.log Oh whoops, forgot cat/vim/less/tail/whatever vim !! Etc
- sandreas 8y agoCool... next thing on my cheatsheet. Thanks.
- emrox 8y agoalso available on git git checkout master git checkout my-branch git pull git checkout - git merge -
- sandreas 8y agoNice! thx
- oddly 8y agoHere are some more useful shell bits. - When prefixing a command with a space, it is not logged in the history. - !$ represents the argument of the previous command. $_ should also work.