This will move foo.c
to the new directory baz
with the parent directory bar
.
mv foo.c `mkdir -p ~/bar/baz/ && echo $_`
The -p
option to mkdir
will create intermediate directories as required.
Without -p
all directories in the path prefix must already exist.
Everything inside backticks ``
is executed and the output is returned in-line as part of your command.
Since mkdir
doesn't return anything, only the output of echo $_
will be added to the command.
$_
references the last argument to the previously executed command.
In this case, it will return the path to your new directory (~/bar/baz/
) passed to the mkdir
command.
I unzipped an archive without giving a destination and wanted to move all the files except `demo-app.zip` from my current directory to a new directory called `demo-app`.
The following line does the trick:
mv `ls -A | grep -v demo-app.zip` `mkdir -p demo-app && echo $_`
ls -A
returns all file names including hidden files (except for the implicit .
and ..
).
The pipe symbol |
is used to pipe the output of the ls
command to grep
(a command-line, plain-text search utility).
The -v
flag directs grep
to find and return all file names excluding demo-app.zip
.
That list of files is added to our command-line as source arguments to the move command mv
. The target argument is the path to the new directory passed to mkdir
referenced using $_
and output using echo
.