Navigating to Commonly/Recently Used Dirs, in Terminal (Unix/OS X) - macos

Would it be possible to save certain locations that I've used recently/commonly (like /folder/folder/folder/) so that I don't have to manually navigate through each dir between my current and destination dir?
Sort of like alt-tab, but for paths. I'm on OS X, but perhaps this can be done using basic Unix skills?
Thanks!

If you set up your shell to save commands history, using Ctrl+R hotkey may save you some time, which performs search of previously executed commands as you type. Another good thing to know is that most shells provide you with file/directory name completion if you press Tab key once/twice, which is also of great help.
EDIT: you can also make some symbolic links inside single (e.g. home) directory to quickly access directories. Use ln -s <path to target file/directory> <path to link> command. Target paths could either be relative or absolute.

One way that works in most shells (but is slightly different for different shells) is the directory stack. You can use pushd to push a directory, popd to pop the top directory from the stack, and dirs to move directories around and switch to directories in the middle of the stack. I just checked, and the man page for pushd on Mac OS X is useless; use the man page for your shell (likely bash) and search for pushd, etc. there.

In Bash, you can add directories to the CDPATH variable. If you try to cd to a directory that doesn't begin with a slash then the directories listed in CDPATH are searched for a matching destination.

In zsh there are a few options.
A shell can keep a stack of the most recent few directories you've cd'ed into if you use setopt AUTO_PUSHD. With completion set up (autoload -U compinit; compinit), type cd + and press tab, then you'll get a numbered list:
~% cd /Library
/Library% cd /System/Library
/System/Library% cd +
1 -- /Library
2 -- /Users/nicholas
So the most recent directory is +1, etc. (You can reverse this, as I do, with setopt PUSHD_MINUS so you use - instead of + and the most recent directory is -1).
Another option is directory hashing; you can create pseudo-"home directories" (~whatever). Some of mine, for example:
hash -d v=/Volumes
hash -d a=/Volumes/BanjoArchive
hash -d pep=/System/Library/Frameworks/Python.framework/Versions/Current
hash -d sp=$(print /Library/Python/*/site-packages(On[1]))
So I can just type cd ~pep or cd pep (if unambiguous) or even pep (if AUTO_CD is set). In situations other than cd, you can use the directory stack with ~ as well, e.g. ~+1 or ~-1.
zsh can even replace shell variables after a ~ with the AUTO_NAME_DIRS option, though I don't use it because it would clutter the variable list. Nevertheless, here's an example:
~%setopt AUTO_NAME_DIRS
~%v=/Volumes
~%cd ~v
~v%pwd
/Volumes
zsh also supports cdpath as one of the other answers mentions. For example, I have:
cdpath=($HOME /Volumes)
so I can just use the name of a mounted volume or directory in my home directory to cd to it.

I stumbled upon Z and it has solved all of my dir-navigating issues.

Either an alias (via placing it into your ~/.bashrc or ~/.profile depending on setup):
alias godocs='cd /home/me/my_docs`
or pushd/popd as #Jeremiah suggests.

Take a look at "Cd Deluxe" for a greatly improved "change directory" command: http://www.plan10.com/cdd/.

Related

How to start fzf from a different directory than the current working directory?

I often use fzf to navigate the filesystem, especially the Alt-c key binding.
When invoked, fzf generates a list from the current working directory.
Is it possible to make fzf generate a list from a specified directory?
I have tried fzf <dir>, but it results in an error (unknown option). Also, I can't find any options like -C <dir> for specifying the start directory.
I had a more general issue which might be useful for you. The following is from a blog post I wrote about it:
Configuring FZF to search useful directories beyond the working directory
I use fzf both as a command line tool and from within Vim using the fzf.vim plugin. It makes finding (and opening) files intuitive, fast, and frees you from needing to remember their location or exact name. By default, fzf searches recursively within the current directory, which is often just what you want. If you need to search for a file in some directory beyond the current working directory you need to specify that path as an argument to fzf, after which it's business as usual (fzf will recursively search the specified directory).
The Problem
It always felt a shame to have to occasionally precisely specify a path in order to get a fuzzy search going... precisely specifying a path is the exact thing that fzf is supposed to unburden your from! My initial approach was to supply the home directory path and let fzf search everything, the home directory path can be specified in only a couple of characters so there's no real burden in that case.
The problem with doing this is that you end up searching a lot of directories which you know don't have the file you want. The main offenders were directories you end up with if you install say, anaconda3. The results would be swamped with thousands of internal files, with very long paths. The long paths tended to 'soak up' any letters I entered in the search, so it was difficult for fzf to filter them out.
The Solution
You can choose which searching tool fzf uses under the hood. The default is the standard linux find command, but you can also use fd, ripgrep or silver searcher. Apart from being a lot faster than the default find, these latter tools respect .ignore files. This means that fzf will skip any files or directories listed in a .ignore file. We can turn this feature to our advantage.
First, we install fd. If you run Ubuntu 19.04 (Disco Dingo) or newer, you can install the officially maintained package:
sudo apt install fd-find
If you use an older version of Ubuntu, you can download the latest .deb package from the release page and install it via:
# adapt version number and architecture
sudo dpkg -i fd_8.2.1_amd64.deb
Now we configure fzf to use fd by adding the following line in your .bashrc:
export FZF_DEFAULT_COMMAND="fdfind . $HOME"
If you're using an older version than Ubuntu 19.10, the above line needs to be modified like so:
export FZF_DEFAULT_COMMAND="fd . $HOME"
Now fzf will always search recursively from the home directory, and respect any .ignore files. So let's make one in the home directory:
touch ~/.ignore
I find that the list of directories that I might conceivably (~15) want to recursively search with fzf is shorter that the list of directories that I would never want searched. The total number of files in the directories I want searched is about 5000 or so - easily handled by fd.
In the .ignore file, I first list all my home directories, each followed by a '/':
# start by igoring every home directory
anaconda3/
arch/
cache/
code/
Desktop/
.
.
.
Then below those, put the directories that you want to be searched, each preceded by a '!' and followed by a '/':
# now un-ignore the ones I care about
!code/
!Desktop/
!documents/
!downloads/
.
.
.
The '!' will 'cancel out' the previous ignore commands.
And there we have it. We can invoke fzf wherever we are in the file system and start typing vague things about the file(s) we have in mind and fzf will search in a set of predefined directories and find it with ease. This completely removes the barrier of thinking where a file might be and how precisely it was named.
N.B. I have noticed that, for some reason, a couple of subdirectories were not showing up in the fzf search, and so I explicitly created some '!path/to/missed/directory/' lines in this section...
N.B. You may be wondering "What if I find myself in an unusual directory not on the list, and want to use fzf?". I had the same concern so I put a couple of aliases in my .bashrc that can toggle the above configuration on and off at will (be sure to use 'fdfind' for Ubuntu 19.10+, as disused above):
# restore fzf default options ('fzf clear')
alias fzfcl="export FZF_DEFAULT_COMMAND='fd .'"
# reinstate fzf custom options ('fzf-' as in 'cd -' as in 'back to where I was')
alias fzf-="export FZF_DEFAULT_COMMAND='fd . $HOME'"
If you're using Vim to create the .ignore file, an easy way to get a list of all the directories in your home directory is the following command:
:.!ls ~/
Append a '/' to all lines by putting the cursor on the first directory in the list and entering the following command:
:.,$ norm A/
Similar to above, insert the '!' before each one by putting the cursor on the first directory in the list and entering the following command:
:.,$ norm I!
Assuming you're using bash or similar, this is built into the default completion options which get installed with fzf: https://github.com/junegunn/fzf#fuzzy-completion-for-bash-and-zsh
tldr; enter start file or directory, append ** and hit Tab. So if you'd enter cd /foo/** then tab opens fzf with /foo as start directory.
edit at the time of writing the commands for which this works are hardcoded in fzf's bash helpers, which is why this works for cat and cd but not for tac or nano. This is the complete list:
awk cat diff diff3
emacs emacsclient ex file ftp g++ gcc gvim head hg java
javac ld less more mvim nvim patch perl python ruby
sed sftp sort source tail tee uniq vi view vim wc xdg-open
basename bunzip2 bzip2 chmod chown curl cp dirname du
find git grep gunzip gzip hg jar
ln ls mv open rm rsync scp
svn tar unzip zip
To add other commands use this in e.g. your .bashrc, after the place where fzf gets sourced (something like [ -f ~/.fzf.bash ] && source ~/.fzf.bash):
__fzf_defc "tac" _fzf_path_completion "-o default -o bashdefault"
Alternatively: open an issue to ask for the commands you want to be added to fzf by default, things like tac and nano are super common anyway.
You can do something like:
find <dir> | fzf
fd . <dir> | fzf
Source.

Navigating with cd and assigning a directory path to a shortcut variable name in Windows Bash

Is it possible to assign a directory path to a shortcut variable name that can be used to access quickly over and over again through commands like cd?
I am navigating consistently between several directories and I would like to avoid typing out the full directory path every time. I recall having the capacity to enter the shortcut for a path to access a commonly used directory in Linux. I was wondering if it is possible to use the same cd [SHORTCUT_DIRECTORY_NAME] in Windows Git-Bash or if there is an alternative permanent solution that would limit typing out the full directory paths.
Here is an example of such command to access C:\Users\[NAME]\Documents\common directory in a linux machine shortened to com:
[USER]#DESKTOP /c/Users
$ cd com
[USER]#DESKTOP /c/Users/[NAME]/Documents/common
$
I have mostly found ways to use .bat files and I'm not sure this applies to Windows. I was thinking my next best bet would be trying to create a Shell script, but any input on the most convenient method would be greatly appreciated.
Thank you!
Environment: Windows 10, Git Bash v. 4.4.12
is this what you require:
you can assign the directory path to a string and do cd $string. Example:
sh-4.4$ dir="/home/cg/root/abc/xyz/tyh/"
sh-4.4$ pwd
/home/cg/root
sh-4.4$ cd $dir
sh-4.4$ pwd
/home/cg/root/abc/xyz/tyh

How can I cd to an alias directory in the Mac OSX terminal

Is there a way to get into an alias directory from shell with the command "cd" ? It always returns that "htdocs" isn't a directory.
Edit: I made the shortcut with the OS GUI -> rightclicked the htdocs directory and chose "Alias..." (i'm using a german OS if it's not alias maybe it's called shortcut in english?) then i moved it to my home directory (because my terminal starts from there when i open it).
All i want is to open my terminal and type "cd htdocs" so that i can work from there.
you can make symbolic link to it.
ln -s EXISTING_PATH LINK_NAME
e.g.
ln -s ~/Documents/books ~/Desktop/
Reference
Enter into a directory through an alias in Mac OS X terminal
All i want is to open my terminal and type cd htdocs so that i can work from there.
The easier approach is probably to ignore the links and add the parent directory of your htdocs directory to the CDPATH environment variable. bash(1) will check the contents of the CDPATH environment variable when you type cd foo to find the foo directory in one of the directories listed. This will work no matter what your current working directory is, and it'll be easier than setting symbolic links.
If the path to your htdocs is located /srv/www/htdocs/, then you could use CDPATH=/srv/www. Then, cd foo would first look for /srv/www/foo/ and change to it if it exists; if not, then it would look for foo in the current working directory and change to it if it exists. (This might get confusing if you have multiple htdocs directories on your system; in that case, CDPATH=.:/srv/www would let you change into a child directory easily but still use the /srv/www/htdocs/ version if no ./htdocs directory is present.)
You can add the CDPATH=/srv/www line to your ~/.bashrc file so it works every time you start a terminal.
I personally use this to quickly work in the directory which is present deep inside one of my Volumes in my Mac.
Open your ~/.bash_profile, create an alias to the directory by adding this:
alias cdh="cd /Volumes/Haiku/haiku/src/apps/superprefs"
Save it, restart your terminal. Now on typing cdh in your terminal should change the working directory to the one mentioned as the alias.
I am not sure how OSX exposes Alias links but since you are using bash you can just create a variable in your .bashrc file.
On its own line put:
htdocs=YourDirectoryPath/
Once you have restarted bash you can just type cd $htdocs
There is a old hint on macworld to do this in a way that is integrated with BASH: Enable 'cd' into directory aliases from the Terminal
Plus, here is an answer that uses this solution on superuser.
You may be able to use osascript to do this -- this command seems to work:
cd "`osascript -e "on run aFile" -e "set aFile to POSIX file aFile as alias" -e "tell application "\""Finder"\"" to return POSIX path of ( ( original item of aFile ) as text ) " -e "end run" path_to_my_Finder_alias 2>/dev/null`"
Basically this command is running an AppleScript that finds the destination path of the argument (path_to_my_Finder_alias) in a subshell, then wraps it in double quotes, and changes the directory to it.
Maybe someone with a little more bash expertise can turn it into a bash alias or function.
try:
alias cdgo=`echo cd /root/go/`
cdgo will run, then get command "cd /root/go/" and enter, and it will change your directory in current terminal process
It works on my centos, no test with osx

mac os x terminal problem faced

oh my god...i faced a big problem...i was created a .bash_profile in ~ folder and then set paths there...bust the big problem is after restarting my bash i see that none of my commands work like LS and RM and etc...
now i dont know how to fix it...some one help me...i need my terminal as soon as possible...
Make sure you are appending to the existing $PATH.
PATH=$PATH:/Users/mthalman/bin
To prevent this happening in the future:
When I edit my environment files (including bashrc, profile, login, and others), I always try starting another shell before quitting my editing environment. This protects me from the possibility of breaking my environment so that I can't log in.
Make sure your PATH includes the usual bin directories: /bin and /usr/bin.
First I would rename ~/.bash_profile to ~/old.bash_profile.
Then open that up in TextEdit (as a plain text document) and verify how you have set your path.
If you would prefer to use vim/emacs/nano/whatever, the act of renaming the file will allow new terminal sessions to use default paths, so from the command line you should be mostly fine.
Then verify you haven't clobbered $PATH as suggested by #Mark Thalman, above.
If you are in a Terminal Window, simply add in the /bin and /usr/bin back in your PATH.
$ PATH="/bin:/usr/bin:$PATH"
That should allow all the basic Unix command to work once more. Or, you can use the full path name for commands:
$ PATH="" #Can't find nothin'
$ ls
bash: ls: command not found.
$ /bin/ls -a #This will work!
. .. .bash_profile foo bar
Don't Reset PATH in your .profile!
As you discovered, you should never reset PATH in your `.bash_profile. Instead, you should always append and prepend to it:
PATH="/usr/local/bin:$PATH"
PATH="$PATH:$HOME/bin"
The first line will prepend /usr/local/bin to PATH which means if a command is in /usr/local/bin and /usr/bin, the /usr/local/bin version will be executed. Many system admins will put alternative base system commands in /usr/local/bin. For example, on Solaris, they might put VIM in /usr/local/bin/vi, so when you edit a file, you're using the improved VIM and not the base VI.
The second line appends your $HOME/bin to the end of $PATH. That means if there's a /bin/ls and you have ~/bin/ls, the /bin/ls will be executed first.
Never set PATH from scratch because each Unix system might have commands that you to access elsewhere in the system. For example, your site might require you to use X11, so you want /usr/X11/bin in your PATH, or you have GIT installed under the /opt/git directory, and you'll need /opt/git/bin in your path.
Sometimes, base utilities like ls might be replaced with upgraded versions of these utilities. On Solaris, you have the base vi and ls command, Most users like the GNU ls command because it uses color and prefer VIM to plain VI. I would included these utilities in /usr/local/bin and prepend that to my PATH.
And now a Word from a Sponsor
As you probably discovered, Finder doesn't list hidden files. That's why you can't see .bash_profile in Finder. You can use some hacks to change this, but it requires you to type them into the terminal window.
I use a Finder replacement called Path Finder. It contains a lot of neat Power User things such as allowing you to see hidden files, treat Packages such as apps as directories, and be able to view protected directories if you have Administrator access. There's a built in terminal and GUI Subversion client.
It's not cheap ($40), but you can download for free and try it out for 30 days.
BTW, I have absolutely no relationship to Cocoatech except as a customer, and I make no money from people buying Path Finder. It's just a tool I use.

Bookmark Directories In Terminal

Looking for a solution to quickly navigate to long paths in a shell (particularly Max OS X Terminal.app).
Say my path is ~/This/Is/A/Really/Long/Path/That/I/Would/Rather/Not/Type/Frequently
Instead of cd ~/This/Is/A/....
I would like to be able to store favorites/bookmark directories so I could do "cd myPath"
Are there any binaries or tools available to do something like this?
I've found the packages 'Apparix' and 'Goto' which together make the stuff dreams are made of for us terminal junkies.
Naturally, I had trouble installing Apparix, but I figured it out in the end.
How To Install Apparix on Mac OS X:
Download the tarball from Apparix's homepage.
Unpack the tarball, cd to the unpacked folder.
Run this command ./configure --prefix=$HOME/local && make && make install.
Run man apparix, scroll down to the heading BASH-style functions, copy everything within that section (delimited with ---) and paste it into ~/.bash_profile.
That's it. You should now have Apparix up and running on OS X (further install info and usage is on Apparix's homepage).
Another solution is to use Bashmarks, which allows you to this
$ cd ~/This/Is/A/Really/Long/Path/That/I/Would/Rather/Not/Type/Frequently
$ s shortname # save current path as `shortname`
$ cd /
$ g shortname # cd to ~/This/Is/A/Really/Long/Path/That/I/Would/Rather/Not/Type/Frequently
You can use aliases (stick them in your ~/.bash_profile if you want them to always load)
alias cd_bmark1='cd ~/This/Is/A/Really/Long/Path/That/I/Would/Rather/Not/Type/Frequently'
Then use by just typing
cd_bmark1
into the console
I know you already found an answer that worked for you, but a couple of more lightweight suggestions that might help others looking for similar things
If your directories are relatively fixed, just long and far away from each other, you can use the CDPATH environment variable to add directories to the search path when typing the "cd" command. If the directory name you try to cd to isn't in the current directory, the other entries in your CD path will also be looked at (and it's also tab complete aware, at least in bash and zsh).
Switching to zsh rather than bash and using the excellent directory stacks abilities. With it, you can maintain a history of directories that you've visited, view the history with the "dh" alias, and easily switch to a directory by using quick shortcuts (ex: cd -3 to switch to the 3rd directory in your history stack).
Why not having a symlink ?
ln -s ~/This/Is/A/Really/Long/Path/That/I/Would/Rather/Not/Type/Frequently bmark
cd bmark
I use to.sh daily to create and navigate bookmarked paths in bash. It supports tag autocompletion and the ability to easily add/remove bookmarks.
https://github.com/Grafluxe/to.sh
Full disclosure, I wrote this tool :)

Resources