Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1441247
  • 博文数量: 165
  • 博客积分: 2068
  • 博客等级: 上尉
  • 技术积分: 2102
  • 用 户 组: 普通用户
  • 注册时间: 2011-08-27 16:07
文章分类

全部博文(165)

文章存档

2018年(1)

2017年(22)

2016年(9)

2015年(22)

2014年(8)

2013年(25)

2012年(53)

2011年(25)

分类: Python/Ruby

2015-10-11 10:16:23

一个命令的输出可以最为另一个命令的输入,而这个命令的输出又会传递给另一个命令。这种命令组合的输出可以储存在一个变量中。
这些命令被称为过滤器,我们使用管道连接每个过滤器,管道操作符是|。

1. 以两个命令的组合为例:
ls | cat -n > out.txt
ls的输出被传给cat -n,后者将通过stdin所接收到的输入内容加上行号,然后将输出重定向到文件out.txt

2.我们可以使用子shell或者反引用的方法将命令序列的输出存储在变量中
子shell:
cmd_output=$(ls | cat -n)
echo $cmd_output
反引用:
cmd_output=`ls | cat -n`
echo $cmd_output

3. 关于子shell
子shell本身是一个独立的进程,可以使用()操作符来定义一个子shell:
pwd;
(cd /bin; ls);
pwd;
当命令在子shell中执行时,不会对当前shell有任何影响;所有的改变仅限于子shell内。
#!/bin/bash
# FileName: test1.sh
pwd
out=$(cd ~;pwd; ls)
echo $out
pwd

chicol@debian:~/scripts$ ./test1.sh 
/home/chicol/scripts
/home/chicol scripts
/home/chicol/scripts
chicol@debian:~/scripts$ 

阅读(995) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~