Shell腳本 (一) 概述、解析器、腳本入門


個人博客網:https://wushaopei.github.io/    (你想要這里多有)

一、 Shell 腳本概述

1、 Shell 的 含義:

Shell 是一個用C語言編寫的程序,它是用戶使用Linux 的橋梁。Shell既是一種命令語言,又是一種程序設計語言。

Shell 是指一種應用程序,這個應用程序提供了一個界面,用戶通過這個界面訪問操作系統內核的服務。

Ken Thompson 的 sh 是第一種 Unix Shell,Windows Explorer 是一個典型的圖形界面 Shell。

Shell 在線工具

2、Shell 腳本

 

Shell 腳本(shell script),是一種為 shell 編寫的腳本程序。

Shell是一個命令解釋器,是一個程序/bin/bash,解釋linux的命令

注意:

  •      shell交互式命令使用
  •      打開終端,一行行敲命令

Shell script  是利用shell的功能所寫的一個程序,這個程序是使用純文本文件,將一些shell的語法與指令寫在里面,然后用正規表示法,管道命令以及數據流重導向等功能,以達到我們所想要的處理目的。

二、Shell 解析器

1、Linux 提供的Shell解析器有:

查看Shell解析器命令:       sudo cat /etc/shells

如下圖:

2、bash 和 sh  的關系:

可見兩者關系為軟連接,sh 最終指向的是 bash

命令: ll | grep bash

3、Centos 默認的解析器是bash

命令: echo $SHELL

三、Shell腳本入門

1、 腳本格式

腳本 以 #!/bin/bash 開頭(指定解析器)

2、 第一個Shell腳本: hellWorld

(1) 需求: 創建一個Shell腳本,輸出helloworld

(2)案例實操

[root@rich wenmin]# mkdir datas
[root@rich wenmin]# cd datas
[root@rich datas]# pwd
/home/wenmin/datas
[root@rich datas]# touch helloworld.sh
[root@rich datas]# vim helloworld.sh 

在 helloworld.sh 中輸入如下內容:

#!/bin/bash

echo "helloworld wenmin"

(3)腳本的常用執行方式: 

第一種: 采用bash 或sh+腳本的相對或絕對路徑(不用賦予腳本+x 權限)

sh+腳本的相對路徑

[root@rich datas]# ll 總用量 4 -rw-r--r-- 1 root root 38 4月 30 20:26 helloworld.sh [root@rich datas]# sh helloworld.sh helloworld wenmin [root@rich datas]# 

sh+ 腳本的絕對路徑

[root@rich datas]# pwd /home/wenmin/datas [root@rich datas]# sh /home/wenmin/datas/helloworld.sh helloworld wenmin [root@rich datas]#

bash + 腳本的相對路徑

[root@rich datas]# bash helloworld.sh 
helloworld wenmin
[root@rich datas]# 

第二種: 采用輸入腳本的絕對路徑或相對路徑執行腳本(必須具有可執行權限+x)

(a)首先要賦予 helloworld.sh 腳本的 +x 權限

[root@rich datas]# ./helloworld.sh
-bash: ./helloworld.sh: 權限不夠
[root@rich datas]# chmod 777 helloworld.sh
[root@rich datas]# ll

(b)執行腳本

相對路徑

[root@rich datas]# ./helloworld.sh 
helloworld wenmin

絕對路徑

[root@rich datas]# /home/wenmin/datas/helloworld.sh 
helloworld wenmin

注意:

           第一種執行方法,本質是bash 解析器幫你執行腳本,所以腳本本身不需要執行權限。

           第二種執行方法,本質是腳本需要自己執行,所以需要執行權限。

3、第二個Shell 腳本: 多命令處理

(1)需求:

   在 /home/wenmin/ 目錄下創建一個wenxing.txt,在wenxing.txt文件中增加 "I love cls".

(2)案例實操:

[root@rich datas]# touch batch.sh [root@rich datas]# vim batch.sh 

在 batch.sh 中輸入如下內容:

#!/bin/bash cd /home/wenmin/ touch wenxing.txt echo "I love cls" >>wenxing.txt 
//執行Shell腳本

[root@rich datas]# ll 總用量 8 -rw-r--r-- 1 root root 80 4月 30 20:52 batch.sh -rwxrwxrwx 1 root root 38 4月 30 20:26 helloworld.sh [root@rich datas]# bash batch.sh 

查看目錄文件及 wenxing.txt 內容

[root@rich wenmin]# ll
總用量 8
drwxr-xr-x 2 root root 4096 4月  30 20:56 datas
-rw-r--r-- 1 root root   11 4月  30 20:52 wenxing.txt
[root@rich wenmin]# cat wenxing.txt 
I love cls


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM