脚本变量的练习

脚本变量的练习

1)统计你的计算机相关信息,包括系统当前时间,主机名,所使用的操作系统,计算机的硬件架构,内核版本

root@wish1 406]# cat b.sh 
#!/bin/bash
echo -e "e[1;31m 关于计算机的信息e[0m"
TIME=`date`
VERSION=`uname -r`
OS=`uname -s`
HOST=`hostname`
echo -e "e[1;32m current time:e[0m" $TIME
echo -e "e[1;32m operating system:e[0m" $OS
echo -e "e[1;32m hostname:e[0m" $HOST
echo -e "e[1;32m kernel versione[0m" $VERSION

2)使用read命令把用户输入赋值给变量,使用unset命令删除一个定义过的变量

[root@wish1 406]# cat c.sh 
#!/bin/bash
read -p "please input your name: " name
echo -e "e[1;32m welcome $name e[0m"
unset name
echo "now variable is null"
if [ -z $name ]
then
	echo "ok"
fi

3)普通变量只能保存一个值,如果希望在同一个变量中保存多个值呢,
可以使用数组的方法,把系统中注册的每一个用户都保存到数组变量中,然后遍历整个数组打印出系统中的所有用户;

root@wish1 406]# cat user.sh 
#!/bin/bash
index=0
for i in  `cut -f 1 -d : /etc/passwd`
do
	user[$index]=$i
	let index=$index+1
done
index=1
for name in "${user[@]}"
do
	echo "$index: $name"
	let index=$index+1
done
echo "************"

原文地址:https://www.cnblogs.com/hanfei-1005/p/5703022.html