0%

Linux基础--shell脚本

最近小白学习了shell脚本的基础编程,感觉有必要对最近所学知识进行一次简单的总结,所以写了这一篇博客,可能会有所不足。请大家指正,后期在学习过后,会进行完善的。
下面先说下shell登陆的两种方式

交互式登录:

  • 直接通过终端输入账号密码登录
  • 使用“su - UserName” 切换的用户
    执行顺序:/etc/profile --> /etc/profile.d/*.sh -->~/.bash_profile --> ~/.bashrc --> /etc/bashrc

非交互式登录:

  • su UserName
  • 图形界面下打开的终端
  • 执行脚本
  • 任何其它的bash 实例
    执行顺序: ~/.bashrc --> /etc/bashrc -->/etc/profile.d/*.sh

关于bash配置文件生效范围

  • 全局配置:

    1
    2
    3
    /etc/profile
    /etc/profile.d/*.sh
    /etc/bashrc
  • 个人配置:

    1
    2
    ~/.bash_profile
    ~/.bashrc

    创建Shell脚本

    利用vim等文本编辑工具创建文本文件 第一行必须包括shell 声明序列:#!
    例如:

    #!/bin/bash
    #!/usr/bin/python
    #!/usr/bin/perl

  • shell 脚本的用途:

    -   1、 自动化执行常用命令
    -   2、执行系统管理和故障排除
    -   3、 创建简单的应用程序
    -   4、创建文本或者文件
    

运行脚本文件

首先先给予文本文件权限:

1
chmod +x $name.sh

直接运行脚本文件./$PATH/$name.sh或者$shell ./$PATH/$name.sh,接下来就是小白简单写了一个简单的脚本文件格式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
[ $# -gt 1 ] && { echo " must be a arg ";exit;}
[ $# == 0 ] && read -p "please input script name: " name || name=$1
[ -e $name ] && { echo "the file is exist , please return the script and input another name"; exit ; }
touch $name
echo "#!/bin/bash
# author:wangnan
# mailbox:*********@163.com
# QQ:********
# blog:http://vinnywang.com
# description:this is for wang
# echo " Your working directory is: $(pwd) "
# date `date`">"$name"
chmod +x "$name"
vim $name
unset name

这个脚本的功能是创建脚本模板,首先是判断运行脚本时是否后加参数,不加的话就退出,加的话,判断是否名字相同,相同的话重新命名另外一个名字,之后自动添加执行权限,并打开该脚本,unset

调试脚本

检测脚本中的语法错误

bash -n /$PATH/$name.sh

调试执行

bash -x /$PATH/$name.sh