【Linux学习七】脚本编程

环境
  虚拟机:VMware 10
  Linux版本:CentOS-6.5-x86_64
  客户端:Xshell4
  FTP:Xftp4

一、多层bash
#.和source都是当前bash

[root@node1 ~]# echo $$
1578

sh01.sh:
echo $$

[root@node1 ~]# . sh01.sh
1578
[root@node1 ~]# source sh01.sh
1578

#在调用bash 进入子bash
[root@node1 ~]# bash sh01.sh
1593

pstree:

 

sh02.sh:

#!/bin/bash
echo $$
pstree

[root@node1 ~]# ./sh02.sh
1594
init─┬─auditd───{auditd}
├─crond
├─master─┬─pickup
│ └─qmgr
├─6*[mingetty]
├─rsyslogd───3*[{rsyslogd}]
├─sshd───sshd───bash───sh02.sh───pstree
└─udevd───2*[udevd]

#!/bin/bash 等同于开启一个子bash,如果不写这一行 默认开启一个bash

注意:搞清父子bash,不同bash执行结果可能不同。

二、重定向
输出重定向操作符
>:重定向 会覆盖
>>:重定向 追加
标准输出重定向:
ls / 1>1.out
标准错误输出重定向:
ls /abc 2>2.out
将标准输出和错误输出重定向到同一个文件里:
先将标准输出定向到文件,然后将标准错误输出重定向到标准输出(左边不能有空格),错误信息会先打印
ls / /abc 1>ls.out 2>&1
或者
ls / /abc >& ls.out
或者
ls / /abc &> ls.out

输入重定向
<<<:从一个字符读数据
<<:将标志之间的换行符之前的内容输入
<:从一个文件读取数据

[root@node1 /]# read aaa<<<abc.txt
[root@node1 /]# echo $aaa
abc.txt

#对换行符敏感
[root@node1 /]# read bbb<<AABB
> mmm
> nnn
> ddd
> AABB
[root@node1 /]# echo $bbb
mmm

[root@node1 /]# cat 0<abc.txt
hello world

[root@node1 fd]# ll
total 0
lrwx------. 1 root root 64 Dec 24 02:38 0 -> /dev/pts/0
lrwx------. 1 root root 64 Dec 24 02:56 1 -> /dev/pts/0
lrwx------. 1 root root 64 Dec 24 02:56 2 -> /dev/pts/0
lrwx------. 1 root root 64 Dec 24 02:56 255 -> /dev/pts/0
#创建百度TCP连接 重定向到输入8文件
[root@node1 fd]# exec 8<> /dev/tcp/www.baidu.com/80
[root@node1 fd]# ll
total 0
lrwx------. 1 root root 64 Dec 24 02:38 0 -> /dev/pts/0
lrwx------. 1 root root 64 Dec 24 02:56 1 -> /dev/pts/0
lrwx------. 1 root root 64 Dec 24 02:56 2 -> /dev/pts/0
lrwx------. 1 root root 64 Dec 24 02:56 255 -> /dev/pts/0
lrwx------. 1 root root 64 Dec 24 03:38 8 -> socket:[32425]
#通过8输入文件 创建到百度HTTP请求
[root@node1 fd]# echo -e "GET / HTTP/1.0\n" 1>&8
#通过8输入文件 查看百度http请求返回
[root@node1 fd]# cat 0<&8

三、变量
本地:
当前shell拥有
生命周期随shell

局部:
只能local用于函数

位置:
$1,$2,${11}
脚本
函数

猜你喜欢

转载自www.cnblogs.com/cac2020/p/10170875.html