shell基础学习

一、shell概述

shell是一个命令行解释器,它接收应用程序/用户命令,然后调用操作系统内核,shell耗时一个功能强大的编程语言,易编写,易调试,灵活性强shell基础学习_第1张图片

  • linux提供的shell解析器有:
    [root@centos100 jdk1.8.0_221]# cat /etc/shells
    /bin/sh
    /bin/bash
    /usr/bin/sh
    /usr/bin/bash
    /bin/tcsh
    /bin/csh
    
  • bash和sh的关系
    [root@centos100 bin]# ll | grep bash
    -rwxr-xr-x. 1 root root     964536 11月 25 2021 bash
    lrwxrwxrwx. 1 root root         10 6月   4 22:00 bashbug -> bashbug-64
    -rwxr-xr-x. 1 root root       6964 11月 25 2021 bashbug-64
    lrwxrwxrwx. 1 root root          4 6月   4 22:00 sh -> bash
    
  • Centos默认的解析器是bash
    [root@centos100 bin]# echo $SHELL
    /bin/bash
    

二、Shell脚本入门

  • 需求:创建一个shell脚本,输出helloworld
  • 案例实操
    #!/bin/bash
    echo "hello world"
    
  • 脚本的常用执行方式
    • 采用bash或sh+脚本的相对路径或绝对路径(不用赋予脚本+x权限)
      [atguigu@centos100 bin]$ bash helloworld.sh 
      hello world
      [atguigu@centos100 bin]$ sh helloworld.sh 
      hello world
      [atguigu@centos100 bin]$ sh /home/atguigu/bin/helloworld.sh 
      hello world
      
    • 采用输出脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x)
      [atguigu@centos100 bin]$ chmod +x helloworld.sh 
      [atguigu@centos100 bin]$ ./helloworld.sh 
      hello world
      
    • 脚本前面加上"."或者source
      [atguigu@centos100 bin]$ . helloworld.sh 
      hello world
      [atguigu@centos100 bin]$ source helloworld.sh 
      hello world
      

      通过bash,sh执行,都是在当前shell中,打开一个子shell来执行脚本内容,当脚本内容结束,则子shell关闭,回到父shell中,使用在脚本路径前面加"."或source的方式,可以使脚本内容在当前shell里执行,而无需打开子shell,这也是为什么每次修改完/etc/profile文件之后,需要source一下的原因,打开子shell的区别在于,环境变量的继承关系,如在子shell中设置的当前变量,父shell是不可见的

三、变量

1、系统预定义变量

  • 常见系统变量:$HOME,$PWD,$SHELL,$USER等
  • 实操
    [atguigu@centos100 bin]$ echo $HOME
    /home/atguigu
    
  • 显示当前shell中所有变量:set
    [atguigu@centos100 bin]$ set
    A=5
    ABRT_DEBUG_LOG=/dev/null
    BASH=/usr/bin/bash
    BASHOPTS=checkwinsize:cmdhist:expand_aliases:extglob:extquote:force_fignore:histappend:interactive_comments:progcomp:promptvars:sourcepath
    BASH_ALIASES=()
    BASH_ARGC=()
    BASH_ARGV=()
    BASH_CMDS=()
    BASH_COMPLETION_COMPAT_DIR=/etc/bash_completion.d
    BASH_LINENO=()
    

    1

2、自定义变量

  • 基本语法
    • 定义变量:变量名=变量值,注意=号前后不能有空格
    • 撤销变量:unset变量名
    • 声明静态变量:readonly变量,注意:不能unset
  • 变量定义规则
    • 变量名称可以由字母、数字、下划线组成,但是不能以数字开头,环境变量名建议大写
    • 等号两侧不能有空格
    • 在bash里,变量默认类型都是字符串类型,无法直接进行数值运算
    • 变量的值有空格,需要使用双引号或单引号括起来
    • 变量的值如果有空格,需要使用双引号或单引号括起来
      [atguigu@centos100 bin]$ C="asher is man"
      [atguigu@centos100 bin]$ echo $C
      asher is man
      [atguigu@centos100 bin]$ C="你好"
      [atguigu@centos100 bin]$ echo $C
      你好
      [atguigu@centos100 bin]$ unset C
      [atguigu@centos100 bin]$ echo $C
      
      [atguigu@centos100 bin]$ readonly U=1
      [atguigu@centos100 bin]$ U=2
      bash: U: 只读变量
      [atguigu@centos100 bin]$ echo $U
      1
      [atguigu@centos100 bin]$ unset U
      bash: unset: U: 无法反设定: 只读 variable
      

3、特殊变量

你可能感兴趣的:(学习,linux,运维,shell)