常用shell小脚本
- Usage函数
function Usage() { cat <<-delimiter Usage: command [-x] [-v] [-z] [files] A short explanation of the operation goese here It might be a few lines long, but shoudn't be excessive delimiter }
- 转换字符
tr a-z A-Z <<delimiter Working directory $PWD uio bnm delimiter
- 重复字符串
b=uiop v=$(printf "%-10s" $b) echo "${v// /$b}" printf "%.s$b" {1..10}
- 转换秒 => hour minute second
function swap_seconds() { if [ "$1" -lt 60 ];then echo "full backup lasts $1 seconds" elif [ "$1" -lt 3600 ];then echo "full backup lasts $[$1/60] minutes $[$1%60] seconds" elif [ "$1" -lt 86400 ];then echo "full backup lasts $[$1/3600] hours $(($1%3600/60)) minutes $[$1%60] seconds" else echo 'full backup took too much time!' fi } swap_seconds $1
function convert_seconds() { local T=$1 local D=$((T/60/60/24)) local H=$((T/60/60%24)) local M=$((T/60%60)) local S=$((T%60)) (($D > 0)) && printf ' %d days' $D (($H > 0)) && printf ' %d hours' $H (($M > 0)) && printf ' %d minutes' $M ((($D > 0 || $H > 0 || $M > 0) && $S != 0)) && printf ' and ' (($S > 0 )) && printf '%d seconds\n' $S } convert_seconds $1
-
# encapsulation function checkCommandExists() { local cmd="$1" if [ -z "$cmd" ]; then echo "Usage: checkCommandExists command" return 1 fi which "$cmd" >/dev/null 2>&1 if [ $? -eq 0 ]; then return 0 fi return 5 } function installPackages() { zypper --quiet refresh --force for package in "$@"; do if ! rpm --verify --quiet "$package"; then if ! zypper --quiet --no-gpg-checks install -y "$package"; then echo -e "\e[31;5;7mpackage $package installation failed!!!\e[0m" exit 5 fi fi done } # check docker existence checkCommandExists docker || { echo -e '\033[7mdocker is not installed!\033[0m' && exit 5; } # prerequisites, to install additional software, just add to this array. declare -a packages=( readline-devel libopenssl-devel libxslt-devel libxml2-devel unixODBC-devel netcat-openbsd libseccomp2 ) # install prequisites installPackages "${packages[@]}"
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律