命令替换如何工作

时间:2015-11-28 09:11:46

标签: linux bash

我正在阅读man bash手册页,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).

但我无法理解它是什么意思。 有人可以在一个例子中解释它。让我们说:

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

我最终进入目录

/dir1/dir2/dir3/

第二个命令(cd !$)的工作原理是什么?

1 个答案:

答案 0 :(得分:1)

$$$!是bash脚本可以使用的参数。

这些参数会自动填充给您。

试试这个

#!/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 : $!"

这给了我输出:

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

很高兴知道后台命令的进程ID,你可以这样做 以下内容如下:

kill -9 7608 #killing the background process.

说完上面的话,做:

cd $$

没有意义。是吗?

但是,在终端中,如果执行echo $$,您将获得进程ID 与终端本身关联的bash shell。是!!爷爷。

enter image description here

此外,您可以在终端中使用$!直线。

enter image description here

它给了我最后一个后台进程的进程ID ls以及是否已完成的额外信息。很酷。不是吗?

相关问题