Linux Shell练习
以下代码参照了网上,自己也有修改。
第一题
题目要求
(要求用 if 结构)在终端下运行程序,首先清屏,然后提示:“input a file or directory name, please!”从键盘输入一个字符串(如:xxx),如果该字符串是目录,则显示“xxx is a directory”; 32 如果该字符串是文件,则显示“xxx is a regular file”;如果该文件是可读的,则显示“xxx is a readable file”;如果该文件是可写的,则显示“xxx is a writable”;如果该文件是可执行的, 则显示“xxx is a executable”;如果既不是目录也不是文件,则显示“This script cannot get the file/directory xxx information”。
源代码
#!/bin/bash
clear
echo "input a file or directory name, please!"
read file
if[ -f $file ] #这里空格要小心
then
echo "$file is a regular file"
if [ -w $file ] #这里空格要小心
then
echo "$file is a writable"
fi
if[ -r $file ] #这里空格要小心
then
echo "$file is a readable file"
fi
if[ -x $file ] #这里空格要小心
then
echo "$file is a executable"
fi
elif [ -d $file ] #这里空格要小心
then
echo "$file is a directory."
else
echo "This script cannot get the file/directory $file information!"
fi
运行截图
第二题
题目要求
(要求用 case 或 if 结构)在终端下运行程序,首先清屏,然后提示“Input your age:”。从 键盘输入你的年龄(如:22),如果年龄在 20-29,则输出“please go to root 101”;如果年龄 在 30-39,则输出“Please go to room 201”;如果年龄在 40-49,则输出“please go to root 301”; 如果年龄在 50-59,则输出“Please go to room 401”;如果年龄在 60-69,则输出“please go to root 501”;如果年龄不在上述范围,则输出“Please wait at the door.”。
源代码
#!/bin/bash
clear
echo "please input your age!"
read age
a=` expr $age / 10 ` # 这里空格要小心
case $a in
2)
echo "Please go to room 101"
;;
3)
echo "Please go to room 201"
;;
4)
echo "Please go to room 301"
;;
5)
echo "Please go to room 401"
;;
6)
echo "Please go to room 501"
;;
*)
echo "Please wait at the door!"
esac
运行截图
第三题
题目要求
(要求用循环结构)程序循环列表为某一目录下的所有子目录和文件,运行程序,列出该目录下的所有文件。
源代码
#! /bin/bash
function ergodic() {
for file in ` ls $1 ` #这里空格要小心
do
if [ -d $1"/"$file ]
then
ergodic $1"/"$file
else
echo $1"/"$file
fi
done
}
INIT_PATH="./test_dir" # ./test_dir指的是当前sh脚本文件路径下的文件夹,根据自己的虚拟机改写
ergodic $INIT_PATH
运行截图
第四题
题目要求
(要求用循环结构)运行文件时,显示文件后所带的参数。例如所编辑的文件名为 shi4.sh, 则运行该文件 shi4.sh She He It,显示 She He It
源代码
#!bin/bash
for arg in "$@"
do
echo $arg
done
运行截图
第五题
题目要求
Shell 编程,判断一文件是不是字符设备文件,如果是将其拷贝到 /dev 目录下。
源代码
#!/bin/bash
echo "please input filename"
read file
if [ -c $file ] #这里空格要小心
then
cp $file /test_dir # 这里我没复制到/dev,图方便就放在了当前文件夹的test_dir文件夹内
else
echo "It's not charactor device file"
fi
运行截图
总结
shell编程对于空格这些我自己平时写python、c的时候不注意的小东西太不友好了= =
大家写的时候注意那里需要空格,那里不需要空格,有的时候程序报错就是因为空格导致的。