一组Linux Shell Scripting小练习

# Linux shell将字符串分割成数组

result=$(facter | awk '/ipaddress/ && !/ipaddress_lo/ {print $1 " " $3}')
array=($result)

# 判断一个变量是否存在(不是判断是否为空)

if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi

# 判断一个变量是否为空

if [ "$var x" = " x" ]; then echo "var is empty"; else echo "var is set to '$var'"; fi
if [ -z $var ]; then echo "var is empty"; else echo "var is set to '$var'"; fi

#系统变量用后还原

# 关于IFS的定义:IFS,Internal Field Separator

# An Internal Field Separator (IFS) is an environment variable that stores delimiting characters.

# It is the default delimiter string used by a running shell environment.

# "$*" expands as "$1c$2c$3", where c is the first character of IFS

# When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable.

# That is, "$*" is equivalent to "$1c$2c...", where c is the first  char‐acter of the value of the IFS variable. 

# If IFS is unset, the parameters are separated by spaces.  If IFS is null, the parameters are joined without intervening separators.

oldIFS="$IFS" 
IFS=" " 
array=($result)
IFS="$oldIFS" 
for i in ${array[@]}; do
echo $i
done

# 使用facter获取一组key-value

# facter的输出有换行符,必须把换行符替换成空格

# 将换行符替换成空格可以使用awk或sed

# awk -v RS="" '{gsub("\n"," ");print}'

# echo -e "2 \n1" | sed ':a;N;$!ba;s/\n/ /g'

result=$(facter | awk '/ipaddress/ && !/ipaddress_lo/ {print $1 " " $3}' | awk -v RS="" '{gsub("\n"," ");print}')
array=($result)
array_length=${#array[@]}

# 输出key

for (( i = 0; i < $array_length; i=i+2 )); do
	echo ${array[$i]}
done

# 输出value

for (( i = 1; i < $array_length; i=i+2 )); do
	echo ${array[$i]}
done

# 输出key-value

for (( i = 0; i < $array_length; i=i+2 )); do
	j=$i+1
	echo "${array[$i]} - ${array[$j]}"
done

--end--

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值