Shell 入門
阿新 • • 發佈:2021-06-23
一、簡介
Shell 是一個命令列直譯器,它接收應用程式/使用者命令,然後呼叫作業系統核心。Shell 還是一個功能強大的程式語言,易編寫、易除錯、靈活性強。
二、Shell 解析器
(1)Linux 提供的 Shell 解析器有:
[root@centos7 ~]# cat /etc/shells /bin/sh /bin/bash /usr/bin/sh /usr/bin/bash /bin/tcsh /bin/csh
(2)bash 和 sh 的關係
[root@centos7 ~]# cd /bin/ [root@centos7 bin]# ll | grep bash -rwxr-xr-x. 1 root root 9645364月 1 2020 bash lrwxrwxrwx. 1 root root 10 4月 26 16:45 bashbug -> bashbug-64 -rwxr-xr-x. 1 root root 6964 4月 1 2020 bashbug-64 lrwxrwxrwx. 1 root root 4 4月 26 16:45 sh -> bash [root@centos7 bin]#
(3)Centos 預設的解析器是bash
[root@centos7 bin]# echo $SHELL
/bin/bash
三、Shell 指令碼入門
1、指令碼格式
指令碼以 #!/bin/bash 開頭(指定解析器)
2、第一個Shell指令碼
(1)需求:建立一個 Shell 指令碼,輸出helloworld
(2)案例實操:
[root@centos7 shell_test]# touch helloworld.sh [root@centos7 shell_test]# vim helloworld.sh 在helloworld.sh中輸入如下內容 #!/bin/bash echo "helloworld"
(3)指令碼的常用執行方式
第一種:採用 bash 或 sh+指令碼的相對路徑或絕對路徑(不用賦予指令碼+x許可權)
#sh+指令碼的相對路徑 [root@centos7 shell_test]# sh helloworld.sh #sh+指令碼的絕對路徑 [root@centos7 shell_test]# sh /home/atguigu/datas/helloworld.sh #bash+指令碼的相對路徑 [root@centos7 shell_test]# bash helloworld.sh #bash+指令碼的絕對路徑 [root@centos7 shell_test]# bash /home/atguigu/datas/helloworld.sh
第二種:採用輸入指令碼的絕對路徑或相對路徑執行指令碼(必須具有可執行許可權+x)
#1、首先要賦予helloworld.sh 指令碼的+x許可權 [root@centos7 shell_test]# chmod 777 helloworld.sh #2、執行指令碼 #相對路徑 [root@centos7 shell_test]# ./helloworld.sh #絕對路徑 [root@centos7 shell_test]# /home/atguigu/datas/helloworld.sh
注意:第一種執行方法,本質是 bash 解析器幫你執行指令碼,所以指令碼本身不需要執行許可權。第二種執行方法,本質是指令碼需要自己執行,所以需要執行許可權。
3、第二個 Shell 指令碼:多命令處理
(1)需求:
在 /opt/shell_test/ 目錄下建立一個 banzhang.txt,在 banzhang.txt 檔案中增加“I love cls”。
(2)案例實操:
[root@centos7 shell_test]# touch batch.sh [root@centos7 shell_test]# vim batch.sh 在batch.sh中輸入如下內容 #!/bin/bash cd /opt/shell_test touch banzhang.txt echo "I love cls" >>banzhang.txt