简体   繁体   中英

how command substitution works

I am reading man bash man page, section Special Parameters :

   $      Expands to the process ID of the shell.  In a () subshell, it expands to the process ID of the cur‐
          rent shell, not the subshell.
   !      Expands to the process ID of the job most recently placed into the background, whether executed  as
          an asynchronous command or using the bg builtin (see JOB CONTROL below).

But I can not understand what is it saying. Can someone please explain it on an example. Lets say I do:

mkdir -p /dir1/dir2/dir3/
cd !$

I end up in directory

/dir1/dir2/dir3/

How exactly the second command ( cd !$ ) works?

$$ and $! are arguments which a bash script can make use of.

These arguments are automagically populated for you.

Try this

#!/bin/bash
echo "My own process id : $$"
ping -n 100 google.com &>/dev/null & 
# Here ping command is run in background -> see the & at the end.
# It detaches itself from the stdin and I have suppressed the output
# using the &>/dev/null
echo "Process id of the command last run in background : $!"

Which gave me the output:

My own process id : 812
Process id of the command last run in background : 7608

It is good knowing the process id of the background command in that you can do things like below later :

kill -9 7608 #killing the background process.

Having said the above stuff, doing :

cd $$

doesn't make sense. Does it?

However, in the terminal, if you do echo $$ , you will get the process ID of the bash shell that is associated with the terminal itself. Yes !! the grandpa.

在此处输入图片说明

Also, You could make use of the $! straightaway in the terminal.

在此处输入图片说明

It gave me the the process id of the last background process that is ls plus the extra information whether it has completed or not. Pretty Cool. Isn't it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM