?使用 function
关键字或直接使用 ()
定义函数。
function my_function {
# 函数体
}
?通过函数名和参数列表来调用函数。
my_function arg1 arg2
通过 $1
, $2
, $3
, ... 来访问传递给函数的参数。
function example {
local param1=$1
local param2=$2
# ...
}
使用 return
语句返回一个值。?
function add {
local result=$(( $1 + $2 ))
echo $result
}
使用 local
关键字声明局部变量,以避免变量在函数外部污染全局命名空间。
function example {
local local_variable="I am local"
# ...
}
#!/bin/bash
# 函数:计算文件行数、单词数和字符数
function analyze_file {
local filename=$1
if [ -f "$filename" ]; then
lines=$(wc -l < "$filename")
words=$(wc -w < "$filename")
characters=$(wc -m < "$filename")
echo "File Analysis for $filename:"
echo "Lines: $lines"
echo "Words: $words"
echo "Characters: $characters"
else
echo "Error: File $filename not found."
fi
}
# 函数:显示文件内容
function display_file {
local filename=$1
if [ -f "$filename" ]; then
echo "File Content of $filename:"
cat "$filename"
else
echo "Error: File $filename not found."
fi
}
# 主程序
echo "Enter the filename:"
read input_file
analyze_file "$input_file"
display_file "$input_file"
function reverse_string {
local input=$1
echo $input | rev
}
reversed=$(reverse_string "Hello")
echo "Reversed string: $reversed"
提取子字符串
function extract_substring {
local input=$1
local start=$2
local length=$3
echo ${input:$start:$length}
}
substring=$(extract_substring "Hello World" 6 5)
echo "Substring: $substring"
function print_array {
local array=("$@")
for element in "${array[@]}"; do
echo $element
done
}
fruits=("Apple" "Orange" "Banana")
print_array "${fruits[@]}"
function backup_file {
local filename=$1
local backup_dir="backup"
if [ ! -d "$backup_dir" ]; then
mkdir "$backup_dir"
fi
cp "$filename" "$backup_dir/"
echo "Backup of $filename created in $backup_dir/"
}
backup_file "example.txt"
function process_files_and_log {
local input_dir=$1
local output_dir="processed_files"
local log_file="process_log.txt"
if [ ! -d "$output_dir" ]; then
mkdir "$output_dir"
fi
touch "$log_file"
for file in "$input_dir"/*; do
if [ -f "$file" ]; then
process_file "$file" "$output_dir"
echo "Processed $file" >> "$log_file"
fi
done
}
function process_file {
local input_file=$1
local output_dir=$2
# 实际处理文件的逻辑
# ...
}
process_files_and_log "/path/to/input_directory"
?计算阶乘
function factorial {
local n=$1
if [ $n -eq 0 ] || [ $n -eq 1 ]; then
echo 1
else
local result=1
for ((i=2; i<=n; i++)); do
result=$((result * i))
done
echo $result
fi
}
result=$(factorial 5)
echo "Factorial of 5 is: $result"
判断一个数是否为质数
function is_prime {
local num=$1
if [ $num -lt 2 ]; then
echo "Not a prime number"
return 1
fi
for ((i=2; i<=num/2; i++)); do
if [ $((num % i)) -eq 0 ]; then
echo "Not a prime number"
return 1
fi
done
echo "Prime number"
return 0
}
is_prime 17