shell--基础教程

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_42813491/article/details/102636110

hello world

  • 新建一个任意后缀名的文件,当然,为了见明知意,可以是.sh,名称就叫hello
  • 进去写点东西
 echo 'hello world'
  • 执行
  • sh hello.sh
  • 或者切换到当前目录, ./hello.sh 然后回车
  • 控制台会打印hello world
  • win系统的可以用git bash ,linux系统的直接就可以

定义变量

  • 字母数字下划线,非数字开头,不需要$定义
  • 定义后使用$前缀引用,也可用${}
  • 分号可省略,单引号双引号皆可
  • 双引号可以输出变量,使用转义符号,单引号不行
name='tom';
echo $name
echo ${name}

定义常量(只读)

  • 注释用#
count=100;
readonly count
count=101 #count: readonly variable


删除变量

count=100;
unset count
echo $count # 不报错,但是打印为空

字符串方法

字符串拼接

  • 注意双引号
str1="hello"
str2="world"
str3="${str1} ${str2}"
echo $str3  # hello world

获取字符串长度

str="hello world"
echo ${#str} # 输出11  空格也算

截取字符串

str="hello"
echo ${str:1:3} # 数字指的是索引,输出ell

查找字符串

str="hello"
echo `expr index "${str}" h`  # 输出 1  从1 计算index

数组

定义数组

arr=(1 2 3 4 5) # 注意  是空格区分

arr1=(   # 可以换行
1
2
3
4
5

)

访问数组–索引访问

arr=(1 2 3 4 5 6)
echo ${arr[1]} # 输出2  

访问数组–全部

arr=(1 2 3 4 5 6)
echo ${arr[*]} # 输出1 2 3 4 5 6
echo ${arr[@]} # 输出1 2 3 4 5 6

获取数组长度

arr=(1 2 3 4 5 6)
echo ${#arr[@]} # 输出6  
echo ${#arr[*]} # 输出6 

运算符

算数运算符

  • 运算符和表达式之间要有空格 1+2 要写成1 + 2
n=1
m=2
echo `expr ${n} + ${m}` # 输出3

条件与关系运算

  • fi 表示if语句结束
a=1
b=2

if [ $a -eq $b ]
then
   echo "$a -eq $b : a 等于 b"
else
   echo "$a -eq $b: a 不等于 b"
fi
if [ $a -ne $b ]
then
   echo "$a -ne $b: a 不等于 b"
else
   echo "$a -ne $b : a 等于 b"
fi
if [ $a -gt $b ]
then
   echo "$a -gt $b: a 大于 b"
else
   echo "$a -gt $b: a 不大于 b"
fi
if [ $a -lt $b ]
then
   echo "$a -lt $b: a 小于 b"
else
   echo "$a -lt $b: a 不小于 b"
fi
if [ $a -ge $b ]
then
   echo "$a -ge $b: a 大于或等于 b"
else
   echo "$a -ge $b: a 小于 b"
fi
if [ $a -le $b ]
then
   echo "$a -le $b: a 小于或等于 b"
else
   echo "$a -le $b: a 大于 b"
fi

逻辑运算符

  • && 相当于and
  • || 相当于or

字符串运算符

a="hello"
b="world"

if [ $a = $b ]
then
   echo "$a = $b : a 等于 b"
else
   echo "$a = $b: a 不等于 b"
fi
if [ $a != $b ]
then
   echo "$a != $b : a 不等于 b"
else
   echo "$a != $b: a 等于 b"
fi
if [ -z $a ]
then
   echo "-z $a : 字符串长度为 0"
else
   echo "-z $a : 字符串长度不为 0"
fi
if [ -n "$a" ]
then
   echo "-n $a : 字符串长度不为 0"
else
   echo "-n $a : 字符串长度为 0"
fi
if [ $a ]
then
   echo "$a : 字符串不为空"
else
   echo "$a : 字符串为空"
fi

在这里插入图片描述

写入文件

echo "hello" > test.txt  # 在当前目录下的test.txt 写入hello

遍历文件夹


function iteratorFolder(){
    for file in `ls $1`
      do
        folder=$1"/"$file
    if [ -d $folder ]
      then
        iteratorFolder $folder
      else
        echo $folder     
    fi
done
}
 
folder="/etc"
iteratorFolder $folder

猜你喜欢

转载自blog.csdn.net/qq_42813491/article/details/102636110