Shell脚本语法与应用(一)

1、简介

Shell 脚本(shell script)简单说也就是一些命令的集合,Linux 的 Shell 分类比较多,我们这里讲的是常用的 Bash( Bourne Again Shell的简称),它也是shell的解释器。

2、声明方式

在文件头部声明#!/bin/bash语句,下面是一个简单查看/usr/local目录文件的脚本

[root@localhost shell]# cat test01.sh 
#!/bin/bash

ls /usr/local

3、执行方式

1、bash + 脚本文件

[root@localhost shell]# bash test01.sh 
bin  etc  games  include  jdk  lib  lib64  libexec  mysql  sbin  share	src  tomcat

2、source + 脚本文件(使用当前的 bash 执行脚本,1和3是新启动一个子bash执行脚本)

[root@localhost shell]# source test01.sh 
bin  etc  games  include  jdk  lib  lib64  libexec  mysql  sbin  share  src  tomcat

3、./脚本文件.sh(需要使用chmod +x 脚本文件.sh授执行权限)

[root@localhost shell]# ./test01.sh
-bash: ./test01.sh: 权限不够
[root@localhost shell]# chmod +x test01.sh 
[root@localhost shell]# ll
总用量 4
-rwxr-xr-x. 1 root root 27 61 13:03 test01.sh
[root@localhost shell]# ./test01.sh
bin  etc  games  include  jdk  lib  lib64  libexec  mysql  sbin  share	src  tomcat

4、IO(输入/输出)

IO有3种类型,分别为标准输入(值为0)、标准输出(值为1)和错误输出(值为2)

4.1、标准输入(值为0)

需要用到read关键字,<<<符号意思是将标准输入重定向到字符串中,可以理解为将test input str值赋值给变量name,然后再使用$name方式取值

[root@localhost shell]# read name 0<<<"test input str"
[root@localhost shell]# echo $name
test input str

4.2、标准输出(值为1)

使用命令ls 1>/tmp/my.log将当前目录的3个文件,以文本形式输入到了my.log日志文件中(一个>符号是覆盖效果)

[root@localhost shell]# ll
总用量 4
-rw-r--r--. 1 root root  0 61 13:58 1.txt
-rwxr-xr-x. 1 root root 27 61 13:03 test01.sh
drwxr-xr-x. 2 root root  6 61 14:00 tmp
[root@localhost shell]# ls 1>/tmp/my.log
[root@localhost shell]# cat /tmp/my.log 
1.txt
test01.sh
tmp

使用命令ls 1>>/tmp/my.log将当前目录的3个文件,以文本形式输入到了my.log日志文件中(两个>>符号是追加效果)

[root@localhost shell]# ls 1>>/tmp/my.log
[root@localhost shell]# cat /tmp/my.log 
1.txt
test01.sh
tmp
1.txt
test01.sh
tmp

4.3、错误输出(值为2)

使用命令ls /abc 2>>/tmp/error.log,因为/abc目录不存在,所有会将命令执行抛出的错误提示信息输入到error.log日志文件中

[root@localhost shell]# ls /abc 2>>/tmp/error.log
[root@localhost shell]# cat /tmp/error.log 
ls: 无法访问'/abc': 没有那个文件或目录

4.4、标准输出与错误输出合并写法

常用写法为ls 1>>/tmp/my.log 2>&1,表示先让标准输出重定向到my.log文件,然后将错误输出绑定到标准输出,这样正确与错误日志都会输出到my.log中

一文搞定Linux常见用法(汇总

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值