bash - 可以混合选项和参数吗?
问题描述
是否可以混合选项(使用 getopts)和参数($1....$10)?
解决方案
getopt
(单数)可以处理混合的选项和参数,以及短选项-s
和长--long
选项以及--
结束选项处理。
在这里查看如何file1
与file2
选项混合并将它们分开:
$ args=(-ab opt file1 -c opt file2)
$ getopt -o ab:c: -- "${args[@]}"
-a -b 'opt' -c 'opt' -- 'file1' 'file2'
典型用法如下:
#!/bin/bash
options=$(getopt -o ab:c: -l alpha,bravo:,charlie: -- "$@") || exit
eval set -- "$options"
# Option variables.
alpha=0
bravo=
charlie=
# Parse each option until we hit `--`, which signals the end of options.
# Don't actually do anything yet; just save their values and check for errors.
while [[ $1 != -- ]]; do
case $1 in
-a|--alpha) alpha=1; shift 1;;
-b|--bravo) bravo=$2; shift 2;;
-c|--charlie) charlie=$2; shift 2;;
*) echo "bad option: $1" >&2; exit 1;;
esac
done
# Discard `--`.
shift
# Here's where you'd actually execute the options.
echo "alpha: $alpha"
echo "bravo: $bravo"
echo "charlie: $charlie"
# File names are available as $1, $2, etc., or in the "$@" array.
for file in "$@"; do
echo "file: $file"
done
推荐阅读
- python - 用其他数字更改数字的第 2、3、4 次出现
- javascript - Why is my page content loading before my header script
- javascript - 如何通过另一个对象数组过滤对象数组并将键/值添加到结果数组?
- r - get() 和 assign() 不适用于 colnames()
- python - matplotlib上的渐变色线
- python - 使用 Python/Pandas 将未知长度的表打印到 CSV 文件
- pandas - 在python中获取最近合并前后30分钟的记录
- terminal - 使用 systemd-run 限制多个进程的 CPU 和内存使用的语法?
- python - 在将列表输入谷歌表格时,我应该如何修复列表索引超出范围错误?
- sendgrid - 收件人服务器阻止电子邮件在 SendGrid 中传递