shell编程for循环练习

1、判断/var/目录下所有文件的类型

for file in $(ls /var);do
  type=$(ls -ld /var/$file | grep -o ^. )
  case $type in
  -)
    echo "/var/$file is a regular file."
    ;;
  d)
    echo "/var/$file is a directory."
    ;;
  b)
    echo "/var/$file is a block special file."
    ;;
  c)
    echo "/var/$file is a character file."
    ;;
  s)
    echo "/var/$file is a socket file."
    ;;
  p)
    echo "/var/$file is a pipe file."
    ;;
  l)
    echo "/var/$file is a link file."
    ;;
  *)
    echo $type
    echo $(ls -l $file)
    ;;
  esac
done

2、添加10个用户user1-user10,密码为8位随机字符

生成随机字符的方法有

# 方法一
echo $RANDOM |md5sum |cut -c 1-8
# 方法二
head -c33 /dev/urandom | base64 | head -c8
# 方法三
openssl rand -base64 33 |cut -c1-8
# 方法四
cat /proc/sys/kernel/random/uuid |cut -c 1-8
#!/bin/bash

echo > /data/users
for username in $(echo user{1..10});do
  useradd $username &> /dev/null
  key=$(head -c33 /dev/urandom | base64 | head -c8)
  if echo $key | passwd $username --stdin &> /dev/null;then
    cat << eof >> /data/users
    $username     $key
eof
  fi
done

3、/etc/rc.d/rc3.d目录下分别有多个以K开头和以S开头的文件;分别读取每个文件,以K开头的输出为文件加stop,以S开头的输出为文件名加start,如K34filename stop S66filename start

for file in $(ls /etc/rc.d/rc3.d);do
  starter=$(echo $file | grep -o '^.' )
  case $starter in
  S)
    echo $file start
    ;;
  K)
    echo $file stop
    ;;
  esac
done

4、编写脚本,提示输入正整数n的值,计算1+2+…+n的总和

read -p "Please input a integer:" num
if echo $num |  grep -E '^[0-9]+$' &> /dev/null;then
  declare -i sum=0
  for inc in $(seq $num);do
  sum+=inc
  done
  echo "1+2+...+$num=$sum"
else
  echo "check your input,and try again."
fi

5、计算100以内所有能被3整除的整数之和

declare -i sum=0
for (( n=1; n<100; n++ ));do
  if let n%3==0;then
  sum+=$n
  fi
done
echo $sum

6、编写脚本,提示请输入网络地址,如192.168.0.0,判断输入的网段中主机在线状态

net=$(echo $1 | grep -oE '^.+\.')
for (( i=2;i<254;i++ ));do
  ip=${net}$i
  if ping -n -c1 $ip &> /dev/null;then
    echo "the host $ip is up."
  else
    echo "the host $ip is down."
  fi
done
uset net
uset ip
uset i

7、打印九九乘法表

for (( i=1;i<=9;i++ )) ;do
  for (( j=1;j<=i;j++ )) ;do
    echo -en "$j*$i=$((i*j)) \t"
  done
  echo
done

8、在/testdir目录下创建10个html文件,文件名格式为数字N(从1到10)加随机8个字母,如:1AbCdeFgH.html

for num in {1..10};do
  letters=$(head -c 38 /dev/urandom | base64 | tr -dc '[[:alpha:]]' | head -c8)
  touch /data/$num$letters.html
done

9、打印等腰三角形

read -p "Please input the triangle's height(rows):" height
if ! { echo $height | grep -E '^[0-9]+$' &> /dev/null; };then
  echo "check your input, and try angain."
  exit
fi
for (( i=1; i<=$height; i++ )) ;do
  for (( j=$height-$i; j>0; j-- ));do
    echo -n ' '
  done
  for (( k=1;k<2*$i; k++ ));do
    echo -n '*'
  done
  echo
done

你可能感兴趣的:(练习)