As part of my workflow, I tend to ll
(alias ll='ls -l'
) into a directory to see if the files I need are there, and after that, I cd
into the same dir to do whatever I had to do.
I would like to add an alias (or bash function) that would allow me to have the same functionality as !!
or sudo !!
. Namely, if I type ll /mnt/Disc1/somedir
, and find the files that I want to work on in that directory, I would like to be able to just type cd !!
(or something similar) so that if I run the hypothetical cd !!
alias, this would change the ll
from the previous command to cd
while keeping the absolut/relative path, and the run the command with se substitution,
so that now I am on /mnt/Disc1/somedir
instead of the dir where I was previously.
Following this answer, I managed to get a working version:
cd "$(echo !-1 | awk '{print $2}')"
If I run this on the terminal it does exactly what I want (echo !-1
prints the last command from history, namely ll /mnt/Disc1/somedir
and after piping this to awk '{print $2}'
it prints the 2nd column, namely /mnt/Disc1/somedir
, so this becomes the argument/parameter for the cd
command).
My problem is defining an alias for this command.
Functions
Most of the answers I have come across suggest using functions as a solution (here for example), while this answer, after the function part, suggests using literal quotes. For a moment I thought that this would solve my problem but I can't get it to work. The main problem I have with functions is that I can't seem to find a way to make the !-1
part work with out me having to explicitly type the path as an argument for the function.
Quote Escaping
From what I have read (mainly this and this), I believe that if I could understand the proper way to escape the quotes, then I should be able to have a working version of the alias that I want. The problem with the answers I have found is that they don't explain the proper way to escape quotes (or special symbols) nor point to a good reference to learn how to do it (like this one that gives many examples but not enough explanation for me to learn the proper way to do it). They just work for the case at hand or give examples that I have been unable to adapt to my case.
As an alternative, I tried to use the cut command (instead of awk) to try to bypass the need for the single quotes around the {print $2}
part. But as you can imagine, to define a different delimiter I had to use quotes...
Edit As pointed out in this answer, I was trying to solve this the wrong way. See @frabjous comment for a working solution.
$_
for the last argument to the previous command.alias mycd='cd $_'
would do the trick, I think. – frabjous Jun 05 '22 at 00:48