Shell 数组定义 ,在Shell中,用括号()来表示数组,
数组元素之间用空格来分隔。由此,定义数组的一般形式为:
node2:/root#cat a2.sh
f01=(1,2,3,4)
echo $f01;
f02=(1 2 3 4)
echo $f02
node2:/root#sh ./a2.sh
1,2,3,4
1
node2:/root#cat a2.sh
f01=(1,2,3,4)
echo $f01;
f02=(1 2 3 4)
echo $f02
echo ${f02[@]}
node2:/root#sh ./a2.sh
1,2,3,4
1
1 2 3 4
使用@或*可以获取数组中的所有元素,例如:
${nums[*]}
${nums[@]}
两者都可以得到 nums 数组的所有元素。
获取数组长度:
利用@或*,可以将数组扩展成列表,然后使用#来获取数组元素的个数,格式如下:
${#array_name[@]}
${#array_name[*]}
node2:/root#cat a2.sh
f01=(1,2,3,4)
echo $f01;
f02=(1 2 3 4)
echo $f02
echo ${f02[@]}
echo ${#f02[@]}
node2:/root#sh ./a2.sh
1,2,3,4
1
1 2 3 4
4
${file##*/}:删掉最后一个 / 及其左边的字符串:my.file.txt
node2:/root#cat a3.sh
aa='/nas/svn/deploy/20200229/afa_20200201.zip'
echo ${aa##*/}
node2:/root#sh ./a3.sh
afa_20200201.zip
node2:/root#cat a4.sh
aa='afe_XXX.zip'
if [[ $aa == *_XXX* ]]
then
echo '1111111'
fi
node2:/root#sh ./a4.sh
1111111
&&是“与”的意思,||是“或者”的意思
if [[ 1 > 3 ]] && [[ 2 > 1 ]]
then
echo 'aaaaaaa'
fi
node2:/root#sh ./a5.sh
node2:/root#
记忆的方法为:
# 是 去掉左边(键盘上#在 $ 的左边)
%是去掉右边(键盘上% 在$ 的右边)
单一符号是最小匹配;两个符号是最大匹配
${file%.*}:删掉最后一个 . 及其右边的字符串:/dir1/dir2/dir3/my.file
node2:/root#cat a6.sh
aa='afe_XXX.zip'
echo ${aa/%_*}
echo ${aa%_*}
node2:/root#sh ./a6.sh
afe
afe