I am slightly unsure as to what you want really, but I interpret your question as wanting a 'one-liner' that captures a list of directories in $HOME
, for example, and then enables you to cd to the first or second directory in that list, or any of them for that matter.
This I think is possible if you place all the directories in an array and then you could cd to any directory in that array, by using, for example, cd "${cdarray[1]}"
, which would actually take you to the second directory in the list, because Bash arrays always start at 0, so index 0 in the array is actually the first directory.
Here's the one-liner I created that you can use; modify it to suit your purposes. I exclude directories from the list that are actually symbolic links ( [[ ! -L "$d" ]]
). You can remove this test if you need to include them and just keep the test for the directory.
This is an example for the $HOME
directory, and I have added $HOME
to the command, so the paths are now absolute, so you will be able to later run cd "${cdarray[1]}"
as a separate command from any location and it will work. If you create it for another directory, just specify that absolute path instead of $HOME
in the command below, unless of course you want it to work only relative to the directory in which it was created.
cdarray=(); for d in *; do [[ ! -L "$HOME/$d" && -d "$HOME/$d" ]] && cdarray+=("$HOME/$d"); done; cd "${cdarray[1]}"
Now, any directories with spaces in their names will be handled successfully.
The indexed array is declared, and then if the found item is a directory and not a symlink, it is added to the array and then after the semi-colon we cd to the directory we want, e.g. cd "${cdarray[1]}"
.
You could add || exit 1
at the end if you used this in a script, but I didn't add that above as it would close the interactive terminal if the cd command failed.