shell脚本编程100例
时间: 2023-07-07 09:34:22 浏览: 49
这里提供一些常见的Shell脚本编程案例,供参考:
1. 输出“Hello World!”
```
#!/bin/bash
echo "Hello World!"
```
2. 求两个数之和
```
#!/bin/bash
echo "Please enter the first number:"
read num1
echo "Please enter the second number:"
read num2
sum=$(($num1 + $num2))
echo "The sum of $num1 and $num2 is $sum"
```
3. 循环输出数字
```
#!/bin/bash
echo "Please enter a number:"
read num
for ((i=1;i<=num;i++))
do
echo $i
done
```
4. 判断一个数是否为偶数
```
#!/bin/bash
echo "Please enter a number:"
read num
if [ $((num%2)) -eq 0 ]
then
echo "$num is an even number"
else
echo "$num is an odd number"
fi
```
5. 判断一个文件是否存在
```
#!/bin/bash
echo "Please enter the file name:"
read filename
if [ -e $filename ]
then
echo "$filename exists"
else
echo "$filename does not exist"
fi
```
6. 输出当前日期和时间
```
#!/bin/bash
echo "The current date and time is $(date)"
```
7. 输出当前用户的用户名和主目录
```
#!/bin/bash
echo "The current user is $(whoami)"
echo "The home directory for the current user is $HOME"
```
8. 拷贝一个文件到另一个目录
```
#!/bin/bash
echo "Please enter the file name:"
read filename
echo "Please enter the destination directory:"
read destdir
cp $filename $destdir
echo "File $filename copied to $destdir"
```
9. 列出当前目录下的所有文件
```
#!/bin/bash
echo "Files in the current directory:"
ls
```
10. 判断一个字符串是否为空
```
#!/bin/bash
echo "Please enter a string:"
read str
if [ -z $str ]
then
echo "The string is empty"
else
echo "The string is not empty"
fi
```
希望这些例子能够帮助您更好地了解Shell脚本编程。