01 Shell Script概述

Shell Script概述

一、什么是Shell

​ Shell就是一个解释器,它的作用就是遵循一定的语法将输入的指令或者命令加以解释并传给系统。类似于windows系统的cmd.exe。

​ 分类:

​ 图形shell(GUI shell)

​ Windows explore

​ linux: x windows, KDE, CDE

​ 命令行shell(CLI shell)

​ bsh

​ bash

​ ksh

​ 常见的命令行Shell

​ Bourne Again Shell (bash):Linux操作系统中常见的shell

​ KornShell (ksh):AIX操作系统中常见的shell

​ Bourne Shell (bsh):Apache的Solaris中常见的shell

二、什么是Shell Script

​ Shell script是利用shell的功能所写的一个程序,这个程序是使用纯文本文件。

​ Windows/Dos下的批处理相似。

​ 就是用各类命令预先放入到一个文件中,方便一次性执行的一个程序文件。

​ 脚本中包含:

​ 变量

​ Shell 语法

​ 命令

#!/bin/bash

#/etc/passwd line count
count=`wc -l /etc/passwd | cut -d' ' -f1'`
num=1
for i in `seq $count` ; do
	u=`head -$i /etc/passwd | tail -1 | cut -d: -f1`
	s=`head -$i /etc/passwd | tail -1 | cut -d: -f7`
	id=`head -$i /etc/passwd | tail -1 | cut -d: -f3`
	if [ $s == '/bin/bash' ]; then
		echo -e "$num\t$u\t$id" >> /tem/test.txt
		num=$[$num+1]
	fi
done

三、第一个Shell Script程序

​ 使用vim/vi命令编辑一个新文件。

​ 新建一个文件test.sh,扩展名为sh(sh代表shell)

​ 第一行声明解释器:

​ 语法:#!——约定的标记(shabang)

​ 如果脚本文件中没有#!这一行,那么它执行时会默认用当前Shell去解释这个脚本

​ 如果#!指定的解释程序没有可执行权限,则会报错“bad interpreter: Permission denied”。

​ 如果#!指定的解释程序不存在,那么会报错“bad interpreter: No such file or directory”。

#!/bin/bash
echo "hello world"

四、怎么执行?

​ 直接执行程序文件:

​ 查看sh文件是否有可执行的权限

​ ./sh文件名

# 查看sh文件权限
[root@localhost ~]# ll
total 4
-rw-r--r--. 1 root root 31 Aug 19 03:43 myshell.sh

# 运行报错,权限不够
[root@localhost ~]# ./myshell.sh
-bash: ./myshell.sh: Permission denied

# 添加执行权限
[root@localhost ~]# chmod u+x myshell.sh 

# 查看权限
[root@localhost ~]# ll
total 4
-rwxr--r--. 1 root root 31 Aug 19 03:43 myshell.sh

# 运行
[root@localhost ~]# ./myshell.sh         
hello world

​ 指定一个解释器去执行sh文件:

​ bash sh文件

# 查看权限
[root@localhost ~]# ll
total 4
-rw-r--r--. 1 root root 31 Aug 19 03:43 myshell.sh

# 没有执行权限,也能执行
[root@localhost ~]# bash myshell.sh
hello world
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值