getopts 处理选项 getopts 是一个内置的命令,用于处理脚本的选项和参数。
#!/bin/bash
usage() { echo "Usage: $0 [-h] [-f file] [-v]" exit 1 }
FILE="" VERBOSE=0
while getopts ":hf:v" opt; do case $opt in h) usage ;; f) FILE=$OPTARG ;; v) VERBOSE=1 ;; \?) echo "Invalid option: -$OPTARG" >&2 usage ;; :) echo "Option -$OPTARG requires an argument." >&2 usage ;; esac done
# 移除已处理的选项和参数 shift $((OPTIND-1))
# 处理剩余的非选项参数 if [ "$#" -gt 0 ]; then echo "Remaining arguments: $@" fi
# 示例:打印文件内容 if [ -n "$FILE" ]; then if [ -f "$FILE" ]; then cat "$FILE" else echo "File not found: $FILE" fi fi
if [ "$VERBOSE" -eq 1 ]; then echo "Verbose mode is on" fiargparse 模块 argparse 模块是 Python 标准库中用于处理命令行参数的模块。
import argparse
def main(): parser = argparse.ArgumentParser(description="Process some integers.") parser.add_argument("-f", "--file", help="Input file path") parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose mode") parser.add_argument("integers", metavar="N", type=int, nargs="+", help="an integer for the accumulator") parser.add_argument("--sum", dest="accumulate", action="store_const", const=sum, default=max, help="sum the integers (default: find the max)")
args = parser.parse_args()
if args.verbose: print("Verbose mode is on")
if args.file: try: with open(args.file, 'r') as f: print(f.read()) except FileNotFoundError: print(f"File not found: {args.file}")
result = args.accumulate(args.integers) print(result)
if __name__ == "__main__": main()[CmdletBinding()] 和 param 块 [CmdletBinding()] 和 param 块可以方便地处理脚本参数。
[CmdletBinding()] param( [string]$File, [switch]$Verbose )
function Show-Usage { Write-Host "Usage: .\your_script.ps1 -File <file_path> [-Verbose]" exit 1 }
if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Host "Verbose mode is on" }
if ($File) { if (Test-Path $File) { Get-Content $File } else { Write-Host "File not found: $File" } }
# 处理剩余的非选项参数 if ($args.Count -gt 0) { Write-Host "Remaining arguments: $($args -join ', ')" }原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。