shell脚本后缀 .sh
创建并打开一个sh文件 vim a.sh (touch a.sh 创建sh文件)
编辑模式 i 退出编辑模式 esc 退出 shift +zz
#!/bin/bash 这个必须写
添加权限 chmod +x 文件名
chmod +x a.sh
代码示例
!/bin/bash
echo 'hello world'
执行文件 ./a.sh
输出结果 hello world
变量
定义变量以及输出变量 使用变量时,变量前需要加上$
#!/bin/bash
name="zhangsan"
echo $name
变量名的命名规范
变量名后的等号左右不能有空格
命名只能使用英文字母,数字和下划线,首个字符不能以数字开头
中间不能有空格,可以使用下划线“_”
不能使用标点符号
不能使用bash里的关键字(可用help命令查看保留关键字)
代码示例
当在脚本中需要执行一些指令并且将执行的结果赋给变量的时候需要使用反引号 `
单双引号:双引号会识别变量,能够实现转义;单引号不会识别变量,不能转义
#!/bin/bash
dt=`date +'%F %T'`
echo $dt
只读变量 readonly
#!/bin/bash
readonly a
a=2
echo $a
执行结果
接收用户输入
read -p
#!/bin/bash
read -p 'qingshuruyige'
echo 'yes'
删除变量
unset
条件判断语句
#!/bin/bash
if [ 2 -eq 1 ] ; then
echo "sad:"
else
echo "sad"
fi
常用的关系运算符
常用算数运算符
写一个脚本,判断当前输入的用户是否存在。如果存在则提示“用户存在”否则提示“用户不存在”
#!/bin/bash
read -p 'input a username:' username
if [ $username = 'root' ]
then
echo 'user is exist'
else
echo 'user is not exist'
fi
循环判断
#!/bin/bash
s=0
for((i=1;i<=100;i=i+1))
do
s=$(($s+$i))
done
echo $s
j=1
sum=0
while [ $j -le 100 ]
do
sum=$(($sum + $j))
j=$(($j+1))
done
echo $sum
~