天天看点

shell学习第二章:Getting Start with shell programming

参考链接:https://bash.cyberciti.biz/guide/Main_Page

1、bash shell分为两种类型的:一种是自带的,另一种是外部的,一般储存在/usr/bin,或者/usr/local/bin路径下

2、type命令可以查明一个命令是build in还是外部二进制可执行文件

type -a ls

type -a history
           

echo命令,既同时是build in,也是外部exe

type -a echo
           

3、如何创建一个脚本文件

To create a shell script:

1、Use a text editor such as vi. Write required Linux commands and logic in the file.
2、Save and close the file (exit from vi).
3、Make the script executable.
4、You should then of course test the script, and once satisfied with the output, move it to the production environment.
5、The simplest program in Bash consists of a line that tells the computer a command. Start up your favorite text editor (such as vi):
           

4、如何运行一个脚本文件

(1)编写一个脚本文件,假如为test.sh

(2)给这个脚本文件修改可执行权限 chmod +x test.sh

(3)假如test.sh在目录happy下,则进入到happy目录下,使用:./test.sh,注意不要忘记前面的“.”了。

#!/bin/bash
echo "Hello, World!" 
echo "Knowledge is power."
           

第一句中的#!指定了特定的解释器,比如这个就指定bash shell。

#!/bin/bash
           

如果你不写这一行的话,那么就会采用默认的shell解释器 /bin/sh,但是推荐用/bin/bash

5、shell中的单行注释采用如下,前面加“#”

# A Simple Shell Script To Get Linux Network Information
# Vivek Gite - 30/Aug/2009
           

多行注释采用如下格式,其中从<<COMMENT1到COMMENT1之间都被注释掉了。

<<COMMENT1
    Master LDAP server : dir1.nixcraft.net.in 
    Add user to master and it will get sync to backup server too
    Profile and active directory hooks are below
COMMENT1
           

6、设置一个脚本的权限

chmod是linux中的一个shell命令,它可以改变一个文件执行状态,一个shell脚本必须有可执行权限.

给一个test.sh脚本赋予可执行权限,让所有人都可以运行

chmod +x test.sh
chmod 0755 test.sh
           

只让脚本文件的所有者可以执行这个脚本文件

chmod 0700 test.sh
chmod u+x test.sh
           

7、查看一个文件的权限

ls -l fileName
           

8、获取chmod的帮助

man chmod
           

9、debug脚本

在编写脚本文件时,在第一行 #!/bin/bash 后面加上“-x”,使得整个脚本文件进入debug模式

#! /bin/bash -x
echo "hello world"
echo "happy day"
           

不想让脚本文件的全部行进入debug模式,只想让部分指令进入debug模式:

set -x开启debug模式,set +x关闭debug模式

#! /bin/bash

###turn on debug mode###
set -x
echo "hello world"
echo "today is $(date)"

###turn off mode ###
set +x
echo "tommorow is $(date)"