I am reading the free book linux 101 hacks.
The book show how to create a new command mkdircd, which create a new directory and then move you to the directory.
so it just to add the following function (down) to the .bash_profile
function mkdircd () { mkdir -p "$@" && eval cd
"\"\$$#\""; }
I have learn script to know that $ mean variable, but I still don't understand how this work.
Can someone explain to me, thanks.
Create a function mkdirce which calls mkdir -p with all function arguments requoted, and if that succeeds, reevaluate the constructed string of cd + " + last argument + ". $# is the argument count $@ is all arguments requoted ($* is all arguments unquoted), $9 is argument nine, so eval $$# is the last argument, '$' plus $#.
1 Like
first thanks.
Second why can't he just write:
function mkdircd () { mkdir -p "$@" && eval cd "$$#"; }
I understand that eventually the eval create those chars.
So why is the use of the special chars \"
Well, you can say $3 or $# and it explodes them, but for $$#, you have to re-explode it, hence eval. It's like
echo $( echo '$'$# )
The inner ksh echo's a $ and $#, and inf $# is 3, the outer ksh echo's $3.
1 Like
because the shell expects $$ to be the pid of the process. \$ forces the shell think of what follows as a variable name.
so
\$ forces $
$# is the number of the last argument
let's pretend the last argument was number five so
\$$# evaluates to $5, which then gets "turned into" the value of argument number 5
1 Like
A \$ or '$' is a literal on the first pass, and a metacharacter on the second pass when they are stripped off.
1 Like