Shell入门介绍及简单案例

1. Shell脚本
1.1 什么是Shell脚本
  • Shell脚本是利用shell的功能所写的一个program,这个程序是使用纯文本文件,将一些shell的语法和命令整合起来,搭配正则表达式管道命令数据重定向,达到我们的目的

  • 书写脚本前的说明

    • 命令是从上而下、从左到右的分析与执行
    • 命令、选项与参数间的多个空格都会被忽略
    • 空白行也会被忽略,由Tab按键所产生的空白同样是空格键
    • 读到一个Enter符号,就尝试该行(该串)命令
    • #可作为注释,任何加在#后面的数据将全部被视为注释文字
    • shell.sh脚本文件必须具备可读与可执行权限
    • 以bash程序来执行,[bash shell.sh] [sh shell.sh]
  • 无名氏的第一个脚本文件

    #!/bin/bash
    # Program:
    #     This program shows "hello world!" in your screen.
    # History:
    # 2021/5/10       Mac      First release
    echo -e "hello world! \a"
    exit 0
    
  • 保持编写脚本的好习惯

    随着学习深入,编写的脚本代码增多、功能变复杂,应当保持在脚本头部写好一些信息

    • 脚本的功能
    • 脚本的版本信息
    • 脚本的作者与联系方式
    • 脚本的版权声明方式
    • 脚本内特殊的命令使用绝对路径来执行
    • 预先声明并设置运行时需要的环境变量
1.2 简单的shell脚本练习
  • 交互式脚本

    #!/bin/bash
    # Program:
    #     User input his first name and last name, program shows his full name.
    # History:
    # 2021/5/10       Mac      First release
    read -p "Please input your first name: " firstname #提示用户输入
    read -p "Please input your last name: " lastname #提示用户输入
    echo -e "\nYour full name is: ${firstname} ${lastname}" #屏幕输出结果
    
  • 随日期变化

    #!/bin/bash
    # Program:
    #     Program creates one file, which named by user's input and date command.
    # History:
    # 2021/5/10       Mac      First release
    # 让用户输入文件名称,并取fileuser变量
    read -p "Please input your filename: " fileuser
    # 对fileuser变量判空, 为空则设置filename为filename,不为空则使用用户输入的值
    filename=${fileuser:-"filename"}
    # 使用date命令获取当前时间
    date=$(date +%Y%m%d)
    # 组装文件名
    file=${filename}${date}
    # 创建文件
    touch "${file}"
    
  • 数值运算

    #!/bin/bash
    # Program:
    #     User input two numbers, program will cross these two numbers.
    # History:
    # 2021/5/10       Mac      First release
    echo -e "input 2 numbers, I will multiply them! \n"
    read -p "first number: " firstnu
    read -p "second number: " secondnu
    total=$((${firstnu}*${secondnu}))
    echo -e "\nThe result of ${firstnu} x ${secondnu} is ==> ${total}"
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值