shell脚本基础练习

编写一个Shell脚本,检查当前目录下是否存在一个名为example.txt的文件。如果存在,打印"File exists!",否则打印"File does not exist!"

#!/bin/bash
if [ -f "example.txt" ]; then
echo "File exists!"
else
echo "File does not exist!"
fi

编写一个Shell脚本,读取用户输入的数字,如果数字大于10,则打印"Number is greater than 10",如果小于等于10,则打印"Number is less than or equal to 10"

#!/bin/bash
read -p "请输入数字: " num
if [ "$num" > 10 ]; then
echo "Number is greater than 10"
elif [ "$num" <= 10 ]; then
echo "Number is less than or equal to 10"
fi

编写一个Shell脚本,使用for循环遍历/etc/目录下的所有文件(只显示文件,不显示目录),并打印文件名。

#!/bin/bash

find /etc -maxdepth 1 -type f | while read -r file; do
    echo "$file"
done

编写一个Shell脚本,使用for循环遍历数字1到10,并对每个数字执行乘法运算(乘以2),然后打印结果

#!/bin/bash

for i in {1..10};
do
    result=$((i*2))
    echo "数字 $i 乘2 等于 $result"
done

编写一个Shell脚本,使用while循环打印从1到10的整数

#!/bin/bash

num=1
while [ $num -le 10 ]
do
    echo $num
    num=$((num + 1))
done

编写一个Shell脚本,要求用户输入一个正整数,然后使用while循环计算该数的阶乘(例如,5的阶乘是54321=120)

#!/bin/bash

read -p "请输入一个正整数:" num
face=1
temp=$num
if [[ $num -lt 0 ]]; then
    echo "请输入正确的数字"
else
    while [ $temp -gt 0 ]; do
    face=$((face * temp))
    temp=$((temp-1))
done
    echo "$num的阶乘是$face"
fi

编写一个Shell脚本,遍历当前目录下所有的.txt文件,并使用if语句检查文件是否为空。如果文件为空,则打印"File is empty!"和文件名

#!/bin/bash
touch hello.txt
for file in *.txt; do
    if [ -f "$file" ]; then
        if [ ! -s "$file" ]; then    
    echo "File is empty! $file"
fi
fi
done

编写一个Shell脚本,从用户那里获取两个数字作为输入,并使用if语句比较它们的大小。根据比较结果,打印出较大的数字。

#!/bin/bash

echo "请输入第一个数字"
read num1
echo "请输入第二个数字"
read num2
if [ "$num1" > "$num2" ]; then
    echo "较大的数字是$num1"
elif [ "$num1" < "$num2" ]; then
    echo "较大的数字是$num2"
else
    echo "两个数字相等"
fi

编写一个Shell脚本,使用for循环遍历当前目录下的所有文件和目录,并统计文件和目录的总数。最后打印出文件和目录的总数

#!/bin/bash

file=0
dir=0
for entry in ./*;do
    if [ -d "$entry" ]; then
    (($dir++))
    elif [ -f "$entry" ]; then
    ((file++))
    fi
done
echo "文件总数 $file"
echo "目录总数 $dir"

编写一个Shell脚本,模拟一个简单的“菜单”程序。程序显示以下选项:

t: 显示当前日期

l: 列出当前目录下的文件

q: 退出程序

使用while循环让用户能够持续选择选项,直到用户选择退出程序为止

#!/bin/bash

display() {
echo "请选择一下选项"
echo "t:显示当前日期"
echo "l:列出当前文件"
echo "q:退出程序"
}
while true;do
    display
read -p "请输入选项" num
case $num in
    t)
    echo "当前日期是$(date)"
    ;;
    l)
    echo "当前文件下的文件有"
    ls -l
    ;;
    q)
    echo "退出选项"
    exit 0
    ;;
    *)
    echo "选项无效"
    ;;
esac
done

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值