if [ -z "$filename" ]; then
echo "Usage: Enter a file path"
exit 2
fi
if [ ! -e $filename ]; then
echo "Usage: No such file, check it and enter again"
exit 3
fi
if [ -f $filename ]; then
echo "It's a common file"
elif [ -d $filename ]; then
echo "It's a directory"
elif [ -L $filename ]; then
echo "It's a symbolic file"
else
echo "Other type"
fi
[iyunv@localhost ~]# bash file.sh
Please Enter a filename:file.sh
It's a common file
for i in {1..10}; do
if id user$i &> /dev/null; then
echo "user$i is exist"
else
useradd user$i && echo "user$i" | passwd --stdin user$i &> /dev/null
echo " add user$i is successed"
fi
done
示例2:判断某路径下所有文件的类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/bash
#judge type of file in some path
for file in $(ls /etc); do
if [ -f /etc/$file ]; then
echo "$file is common file"
elif [ -d /etc/$file ]; then
echo "$file is directory file"
elif [ -L /etc/$file ]; then
echo "$file is symbolic file"
else
echo "$file is oth type"
fi
done
示例3:打印九九乘法表:
1
2
3
4
5
6
7
8
9
#!/bin/bash
#9X9 multiplication
for i in {1..9}; do
for j in $(seq 1 $i); do
echo -e -n "${i}x${j}=$[$i*$j]\t"
done
echo
done
(4)for循环的特殊用法:
for ((控制变量初始化;条件判断表达式;控制变量的修正表达式));do
循环体
done
declare -i i=0
declare -i evensum=0
declare -i oddsum=0
while [ $i -le 100 ]; do
if [ $[$i%2] -eq 0 ]; then
evensum=$[$evensum+$i]
else
oddsum=$[$oddsum+$i]
fi
let i++
done
echo "even number sum is $evensum"
echo "odd number sum is $oddsum"
[iyunv@localhost ~]# bash sum.sh
even number sum is 2550
odd number sum is 2500
②while循环的特殊用法(遍历文件中的每一行)
while read line; do
循环体
done < /PATH/FROM/SOMEFILE
依次读取/PATH/FROM/SOMEFILE文件中的每一行,且将行赋值给变量line;
示例:找出其ID号为偶数的所有用户,显示其用户名及ID号;
1
2
3
4
5
6
7
8
9
#!/bin/bash
#ouput even number id
while read line; do
if [ $[`echo $line | cut -d: -f3` % 2] -eq 0 ]; then
echo -e -n "username: `echo $line | cut -d: -f1`\t"
echo "uid: `echo $line | cut -d: -f3`"
fi
done < /etc/passwd
declare -i i=0
declare -i sum=0
until [ $i -gt 100 ]; do
let i++
if [ $[$i%2] -eq 1 ]; then
continue
fi
let sum+=$i
done
echo "even number sum is $sum"
print(){
echo "your choice is $1"
}
read -p "Please enter one、two、three or four:" num
case $num in
one)
print 1
;;
two)
print 2
;;
three)
print 3
;;
four)
print 4
;;
esac
[iyunv@localhost ~]# bash function.sh
Please enter one、two、three or four:one
your choice is 1
[iyunv@localhost ~]# bash function.sh
Please enter one、two、three or four:two
your choice is 2
declare -a arry
arry=(tom jery joe)
for ((i=0; i<=${#arry[@]}; i++)) do
echo "${arry[$i]}"
done
echo "array length: ${#arry[@]}"
[iyunv@localhost ~]# bash array.sh
tom
jery
joe
#!/bin/bash
#
declare -a num
for i in {0..9}; do
num[$i]=$RANDOM
done
echo ${num
}
for((i=0;i<=9;i++)); do
for((j=$[${i}+1];j<10;j++)); do
if [ ${num[$i]} -gt ${num[$j]} ]; then
a=${num[$i]}
num[$i]=${num[$j]}
num[$j]=$a
fi
done
done
echo ${num