常用 Shell 脚本示例 - 入门指南
- HelloWorld 脚本:
#!/bin/bash
echo 'Hello World!'
- 读取用户输入并输出脚本:
#!/bin/bash
echo 'Please enter your name:'
read name
echo 'Hello $name!'
- 循环脚本:
#!/bin/bash
for i in {1..10}
do
echo 'Count: $i'
done
- 判断是否存在指定文件脚本:
#!/bin/bash
if [ -f '/path/to/file' ]
then
echo 'File exists.'
else
echo 'File does not exist.'
fi
- 判断两个数大小关系脚本:
#!/bin/bash
echo 'Enter two numbers:'
read num1
read num2
if [ $num1 -gt $num2 ]
then
echo '$num1 is greater than $num2'
elif [ $num1 -eq $num2 ]
then
echo '$num1 is equal to $num2'
else
echo '$num1 is less than $num2'
fi
- 计算两个数的和脚本:
#!/bin/bash
echo 'Enter two numbers:'
read num1
read num2
sum=$(($num1 + $num2))
echo 'The sum of $num1 and $num2 is: $sum'
- 判断文件夹是否存在脚本:
#!/bin/bash
if [ -d '/path/to/folder' ]
then
echo 'Folder exists.'
else
echo 'Folder does not exist.'
fi
- 删除指定文件脚本:
#!/bin/bash
rm /path/to/file
echo 'File deleted.'
- 复制指定文件脚本:
#!/bin/bash
cp /path/to/source /path/to/destination
echo 'File copied.'
- 输出当前系统时间脚本:
#!/bin/bash
now=$(date +'%T')
echo 'Current time: $now'
原文地址: https://www.cveoy.top/t/topic/nFOZ 著作权归作者所有。请勿转载和采集!