---
title: "linux复习笔记之bash shell (5) 关于减号-的作用"
author: "eksliang"
date: "2014-08-18T17:58:03Z"
tags: []
categories: ["研发管理"]
slug: "linux-bash-shell-5"
draft: false
lastmod: "2014-08-28T09:25:57Z"
id: 2105677
url: "https://eksliang.iteye.com/blog/2105677"
---

转载请出自出处：[http://eksliang.iteye.com/blog/2105677](/blog/2105677)   

    管道命令在bash的连续处理程序中是相当重要的，尤其在使用到前一个命令的studout（标准输出）作为这次的stdin（标准输入）时，就显得太重要了，某些命令需要用到**文件名**，例如上篇文档的的切割命令（split）、还有tar（打包）命令等等！这时这个文件就承当studout或者stdin,这个时候这个studout或者stdin就可以用减号（-）来替代

 **实例一：使用ls -al /将输出的信息中，没3行记录成一个文件**

```
[root@bogon bash]# ls -al / | split -l 3 - s
[root@bogon bash]# wc -l s*
   3 saa
   3 sab
   3 sac
   3 sad
   3 sae
   3 saf
   3 sag
   2 sah
  23 total
#一般来说，如果需要stdout（标准输出）/stdin（标准输入）,但偏偏又没有文件，有的只是“-”时，那么那个“-”就会被当做stdout或者stout
```

 

实例二：tar -cvf  tarName.tar ./bash 本来是这样的，看我怎么用“-”来替他**文件**的标准输出

```
[root@bogon ~]# tar -cvf   ./bash
tar: Cowardly refusing to create an empty archive
Try `tar --help' or `tar --usage' for more information.
#这里报错了，没有办法，因为语法错误
[root@bogon ~]# tar -cvf  - ./bash 
./bash/
./bash/sag
./bash/saf
./bash/sae
./bash/aa.txt
./bash/sab
./bash/saa
./bash/sad
./bash/cc.txt
./bash/bb.txt
./bash/test.txt
.....
#看到了没有这个时候用”-“替代了本来输出到文件，而标准输出到了屏幕
```

 

    实例三：综合实例

```
[root@bogon ~]# tar -cvf - ./bash | tar -xvf -
./bash/
./bash/sag
./bash/saf
......！（省略）
./bash/saf
./bash/sah
./bash/sac
tar: ./bash: file changed as we read it
./bash/sae
.......!省略）
./bash/sah
./bash/sac
```

  上面这个例子是说我将./bash这个文件打包，但是打包的文件不是记录到文件，而是传送到标准输出（stdout）;经过管道后，将tar -cvf - ./bash传给后面的tar -xvf -。后面这个“-”则是取用前面一个命令的stdout作为stdin,因此这里就不需要使用文件了，这是很常见的例子，因为我们写脚本的时候，就不要去写个临时文件了。