shell-脚本

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

一、xxx

二、控制语句

1. if

2.for

3.while

4.util

5.case

三、数组

例子

1.打印数组

linux shell 中数组的定义和for循环遍历

#!/bin/bash

arr=("0" "1" "2" "3" " "c" "e" "e" "f")
 
for value in ${arr[@]}
do
  echo $value
done


# 或者采取如下方式
echo "----------------------second way----------------------"

for (( i = 0 ; i < ${#arr[@]} ; i++ ))
do
  echo ${arr[$i]}
done

2.字符串转数组

推荐转数组 默认使用空格

例1:

str="123 1aaa bbb  ccc"
arr=(${str})
echo "arr length:" ${#arr[@]}
for s in ${arr[@]}
do
    echo $s
done

输出

arr length: 4
123
1aaa
bbb
ccc

例2

str="i,like,you,csdn"
arr=(${str//,/ })

for s in ${arr[@]}
do
    echo $s
done
str="a b  c   d e"
arr=($str)
for s in ${arr[@]}
do
    echo $s
done

输出

i
like
you
csdn
a
b
c
d
e

例3

a="one,two,three,four"
OLD_IFS="$IFS" 
IFS="," 
arr=($a) 
IFS="$OLD_IFS" 
for s in ${arr[@]} 
do 
    echo "$s" 
done

输出

one
two
three
four

例4

#!/usr/bin/env bash

printFun() {
print $1
}

for temp in 1 2 3 10
do
printFun ${temp}
done

my_array=(A B “C” D)

数组长度${#my_array[@]} ${#my_array[*]}

#!/bin/bash
print "array length:" ${#my_array[*]}
print "array length:" ${my_array[@]}
#循环数组
for temp in ${my_array[*]}
do
    print ${temp}
done

my_array=(
ax1.txt
/abc/file.txt
aaa
)
#循环数组
for temp in $my_array
do
    print ${temp}
done
my_array=(
ax1.txt
/abc/file.txt
aaa
)
#循环数组
for temp in $my_array
do
    echo ${temp}
done

str="123456789abcdef"
echo ${str:1:3}

数组转字符串

arr=(v1 v2 v3 ...vn)
str=''
for i in ${arr[@]};do $str=$str$i done
echo $str
展开阅读全文

没有更多推荐了,返回首页