练习题
1.使用for循环将接收到的参数打印出来
#!/bin/bash
for x in $0 $@
do
if [ $x = $0 ]
then echo ${x##*/}
else
echo $x
fi
done
2.使用while和until计算1+2+3+···+100的值
#!/bin/bash
myvar=0
sum=0
while [ $myvar -ne 100 ]
do
myvar=$(($myvar+1))
sum=$(($sum+$myvar))
done
myvar=0
sum=0
until [ $myvar -eq 100 ]
do
myvar=$(($myvar+1))
sum=$(($sum+$myvar))
done
echo "sum-until=$sum"
3.将该目录下所有的.c文件改名为.d文件
#!/bin/bash
for x in *.c
do
mv $x ${x%%.*}.d
done
done
echo "sum-while=$sum"
4.执行该.sh文件时,输入两个参数,实现建立在该目录下,新建n个某格式的文件,如 4个jpg文件:1.jpg 2.jpg 3.jpg 4.jpg
#!/bin/bash
var=0
while [ $var -ne $1 ]
do
var=$((var+1))
touch $var.$2
done
5.指定目录,将目录下某格式的文件重命名,并加上前缀,如图片1.jpg
#!/bin/bash
var=0
if [ -e $1 ]
then
if [ -d $1 ]
then
for file in $1//*.$2 #此处一个/
do
echo $file
var=$(($var+1))
mv $file $1/$3$var.$2
done
else
echo "not directory"
fi
else
echo "not exit"
fi
6.截取文件名
#!/bin/sh
echo -n 'input a filename: '
read filename
echo extension1:${filename##*.}
echo extension2:${filename#*.}
echo filename:${filename%%.*}
7.'' `` 和$()对变量定义时起的作用
#!/bin/bash
cmd='ls'
echo ''$cmd
cmd=`ls`
echo ``$cmd
cmd=$(ls)
echo $cmd
8.判断文件类型
#!/bin/bash
read -p "enter a filename:" filename
if [ ${filename##*.} = gz ]
then echo ${filename} is a tar ball.
elif [ ${filename##*.} = c ]
then echo ${filename} is a c source.
else
echo ${filename} is not a tarball or a c source.
fi
9.判断文件的属性
#!/bin/bash
read -p "enter a filename:" filename
if [ -e ${filename} ]
then echo -n " ${filename} is a "
if [ -r ${filename} ]
then echo -n readable.
fi
if [ -w ${filename} ]
then echo -n writable.
fi
if [ -x ${filename} ]
then echo -n excutable.
fi
if [ -d ${filename} ]
then echo -n directory.
fi
if [ -f ${filename} ]
then echo -n normal file.
fi
if [ -L ${filename} ]
then echo -n link file.
fi
echo
else
echo ${filename} does not exit.
fi
阅读(1857) | 评论(0) | 转发(2) |