#!/bin/bash
#The printf of Linux termnal,Include "echo,printf"
#author by woon
echo "The shell\`s name is $0"
#examples of echo,printf
#默认打印。输出换行
echo "Hello World!"
echo 'Hello World!'
#echo -n参数接受不换行输出
echo -n "Hello World"
echo "Hello World"
#-e参数接受双引号内字符串的转移列表
echo "Hello\tWorld!"
echo -e "Hello\tWorld!"
#printf使用文本或由空格分割的参数,可指定输出的宽度、对其方式等,可以格式化输出,默认情况下,printf不输出换行
printf "%-5s %-10s %-4s\n" No. NAME Mark
printf "%-5s %-10s %-4s\n" 1 Lee 80
printf "%-5s %-10s %-4.2f\n" 2 Woon 90.456
printf "%-5s %-10s %-4.2f\n" 3 James 85.654321
printf "%-5s %-10s %-5.3f\n" 4 Jeff 85.123789
运行结果:
The shell`s name is shell_print.sh
Hello World!
Hello World!
Hello WorldHello World
Hello World!
-e Hello World!
No. NAME Mark
1 Lee 80
2 Woon 90.46
3 James 85.65
4 Jeff 85.124
#!/bin/bash
#为/etc/passwd生成一个MD5并校验,在生成MD5前检查/etc/passwd文件是否已经被排过序
sort -C /etc/passwd
if [ $? -eq 0 ]; then
echo "Sorted"
else
echo "Unsorted!"
md5sum /etc/passwd > passwd.md5
fi
md5sum -c passwd.md5
7、生成随机数
$RANDOM生成一个随机数;date +%s%N获取随机数字字符串
脚本如下:
#!/bin/bash
#创建example目录,在该目录下批量生成10个日志文件,日志文件名包含10个随机小写字母和固定字符串example;当前用户不具有权限,需要设置权限
if [ ! -d /example ]; then
echo "centos"|sudo -S mkdir /example
echo "centos" | sudo -S chown centos:centos /example -R
fi
#产生随机数$RANDOM,或uuidgen命令或者用MD5sum,然后替换
for num in $(seq 1 10)
do
touch /example/$(echo $RANDOM | md5sum |tr "0-9" "a-z"|cut -c 1-10)_example.log
done
8、根据扩展名切分文件名
#!/bin/bash
#shell name:shell_split.sh
#切分文件名并批量重命名或移动,比如图形文件等
num=1;
for img in *.jpg *.img
do
mv $img image-$num.{img##*.} 2>/dev/null
if [ $? -eq 0 ]; then
echo "Rename $img to image-$num.${img##*.}"
let num++
fi
done
9、列举文件类型统计信息
给出一个路径,统计该路径下各文件类型的数量
#!/bin/bash
#shell name:shell_filestat.sh
#列举文件类型数量
if [ $# -ne 1 ];
then
echo -e "$0 path\nexample:$0 /etc/"
else
path=$1
declare -A array;
while read line;
do
#echo $(file -b $line)
ftype=$(file -b $line)
let array["$ftype"]++;
done< &2 ; exit 1
fi
checkForCmdInPath "$1"
case $? in
0 ) echo "$1 found in PATH" ;;
1 ) echo "$1 not found or not executable" ;;
2 ) echo "$1 not found in PATH" ;;
esac
exit 0