shell脚本入门1

一、什么是shell脚本

通过终端输入命令来完成一些常用的操作
但一条一条输入命令,很麻烦
将所有命令放到一个文件里面,然后直接运行这个文件,这就是shell脚本
shell脚本提供数组、循环、条件判断等功能
shell脚本一般是linux运维或系统管理员要掌握的,嵌入式开发人员掌握最基础的部分即可

二、shell脚本写法

shell脚本是一个纯文本文件
命令从上而下,一行一行的开始执行
shell脚本扩展名为.sh
shell脚本的第一行一定是下面的这种写法,表示使用bash

#!/bin/bash

三、shell脚本语法

3.1、第一个shell脚本

#!/bin/bash
echo "hello world"

3.2、交互试shell脚本

3.2.1、shell脚本 变量的输入和打印

#!/bin/bash
echo "input your name"
read name #输入
echo "your name is" $name
echo "your name is $name"

3.2.2、一次读取两个变量,一次打印两个变量

#!/bin/bash
read -p "input your age and height, with space:" age height
echo "your age is $age, your height is $height"

3.3、shell脚本的数值计算,计算只能计算整数

#!/bin/bash
read -p "input two int num:" first_num second_num
echo "input two int num"
read -p "input first_num:" first_num
read -p "input second_num:" second_num
total=$(($first_num+$second_num))
echo "$first_num + $second_num = $total"

3.4、test命令

#!/bin/bash
read -p "input file name:" filename
test -e $filename && echo "$filename exist" || echo "$filename not exist"

补充:&&和||命令

#!/bin/bash
echo "input two string"
read -p "first string:" first_str
read -p "secode string:" second_str
test $first_str == $second_str && echo "first_str == second_str" || echo "first_str != second_str"

3.5、中括号[]判断符

#!/bin/bash
echo "input two string"
read -p "first string:" first_str
read -p "secode string:" second_str
[ "$first_str" == "$second_str" ] && echo "first_str == second_str" || echo "first_str != second_str"

3.6、默认变量

0   0~ 0 n:表示shell脚本的参数,包括shell脚本命令本身,shell脚本命令本身为$0
$#:#表示最后一个参数的标号
$@:表$1、$2、$3…

#!/bin/bash
echo "file name:" $0
echo "total param num:" $#
echo "whole param:" $@
echo "first param:" $1
echo "second param:" $2

例如./myshell.sh 10086 call
代码执行运行结果:
file name: ./myshell.sh
total param num: 2
whole param: 10086 call
first param: 10086
second param: call

补充
#shell脚本中进行多行注释,可使用如下指令

#!/bin/bash
<< 'COMMENT' 
COMMENT

举例

#!/bin/bash
echo "hello world"
<< 'COMMENT' 
echo "input your name"
read name
echo "your name is" $name
echo "your name is $name"
COMMENT
echo "hello"

四、参考资料

该笔记大部分内容来自学习正点原子视频课程shell脚本入门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值