当前位置: 首页 > news >正文

shell_45.Linux在脚本中使用 getopt

在脚本中使用 getopt

$ cat extractwithgetopt.sh 
#!/bin/bash 
# Extract command-line options and values with getopt 
# 
set -- $(getopt -q ab:cd "$@") 
# 
echo 
while [ -n "$1" ] 
do case "$1" in -a) echo "Found the -a option" ;; -b) param=$2 echo "Found the -b option with parameter value $param" shift;; -c) echo "Found the -c option" ;; --) shift break;; *) echo "$1 is not an option" ;; esac shift 
done 
# 
echo 
count=1 
for param in $@ 
do echo "Parameter #$count: $param" count=$[ $count + 1 ] 
done 
exit 
$
$ ./extractwithgetopt.sh -ac 
Found the -a option 
Found the -c option 
$
$ ./extractwithgetopt.sh -c -d -b BValue -a test1 test2 
Found the -c option 
-d is not an option 
Found the -b option with parameter value 'BValue' 
Found the -a option 
Parameter #1: 'test1' 
Parameter #2: 'test2' 
$

目前看起来相当不错。但是,getopt 命令中仍然隐藏着一个小问题。看看这个例子:

$ ./extractwithgetopt.sh -c -d -b BValue -a "test1 test2" test3 
Found the -c option 
-d is not an option 
Found the -b option with parameter value 'BValue' 
Found the -a option 
Parameter #1: 'test1 
Parameter #2: test2' 
Parameter #3: 'test3' 
$ 


getopt 命令并不擅长处理带空格和引号的参数值。它会将空格当作参数分隔符,而不是根
据双引号将二者当作一个参数。好在还有另外的解决方案。

http://www.lryc.cn/news/203984.html

相关文章:

  • 2023-8-20 CVTE视源股份后端开发实习一面
  • 二叉树进阶
  • 前端性能优化 - 虚拟滚动
  • 手写 Promise(1)核心功能的实现
  • 深入探究Java内存模型
  • 深度学习 | Pytorch深度学习实践 (Chapter 10、11 CNN)
  • 谈谈你对spring boot 3.0的理解
  • 【大数据】Hadoop
  • Spring实例化源码解析之Bean的实例化(十二)
  • git常用的几条命令介绍
  • 使用VisualSVN在Windows系统上设置SVN服务器,并结合内网穿透实现公网访问
  • 第18章 SpringCloud生态(三)
  • leetcode:2347. 最好的扑克手牌(python3解法)
  • 2007-2022 年上市公司国内外专利授权情况数据
  • 安全渗透测试网络基础知识之路由技术
  • 【大数据】Kafka 实战教程(二)
  • React 框架
  • 数据结构与算法之图: Leetcode 133. 克隆图 (Typescript版)
  • illuminate/database 使用 一
  • 前端koa搭建服务器(保姆级教程)——part1
  • js逆向第一课 密码学介绍
  • Dynamic DataSource 多数据源配置【 Springboot + DataSource + MyBatis Plus + Druid】
  • MyBatis:配置文件
  • ARM,基础、寄存器
  • FC-TSGAS-1624 CP451-10 MVI56E-MNETC IC697CMM742
  • 异或运算.
  • NewStarCTF2023week4-逃(反序列化字符串逃逸)
  • PyTorch Tensor 形状
  • RabbitMQ运行机制和通讯过程介绍
  • UE4 TextRender显示中文方法