bash - 使用 OPTARG 作为 shell 脚本中的变量,无论参数的顺序如何
问题描述
假设我有一个像这样的脚本:(我们称之为 test.sh)
#!/bin/sh
function php() {
printf "The rhost is ${RHOST} and the lport is ${LPORT}"
}
while getopts "hr:l:s:" arg; do
case $arg in
h)
printf "Usage\n"
;;
r)
RHOST=$OPTARG
;;
l)
LPORT=$OPTARG
;;
s)
SHELL=$OPTARG
if [[ "$SHELL" == "php" ]] || [[ "$SHELL" == "PHP" ]] ; then
php
fi
;;
esac
done
如果我像“test.sh -r 10 -l 4 -s php”这样运行我的脚本
我的脚本会按照我的意愿执行...
但是,如果我像“test.sh -s php -r 10 -l 4”一样运行它
rhost 和 lport 变量永远不会进入 php 函数。我意识到这是因为它首先被调用。但是,我的问题是,如何编写脚本,以便无论参数运行方式的顺序如何,我仍然可以使用 rhost 和 lport 作为变量?
我也尝试过使用 shift,但我猜这不是答案,或者我将 shift 命令放在错误的位置。
解决方案
将“if”逻辑移出开关/案例:
#!/bin/sh
function php() {
printf "The rhost is ${RHOST} and the lport is ${LPORT}"
}
while getopts "hr:l:s:" arg; do
case $arg in
h)
printf "Usage\n"
;;
r)
RHOST=$OPTARG
;;
l)
LPORT=$OPTARG
;;
s)
SHELL=$OPTARG
;;
esac
done
if [[ "$SHELL" == "php" ]] || [[ "$SHELL" == "PHP" ]]
then
php
fi
推荐阅读
- laravel - 如何在函数参数中使用模型来减少 laravel 中的代码?
- flutter - 我想在脚手架的中心有一个 TapBar
- google-cloud-functions - GhostScript:在单次阅读中裁剪 pdf 的多个区域?
- python - 我是编程新手,在这段代码中有一个我不明白的错误
- java - 如何在eclipse项目aosp android中解决so文件映射
- javascript - 更新 json 文件中的值
- android - java.net 无法解析域名
- firebase - 在 Flutter 中创建时获取 Firebase 实体密钥
- node.js - 错误:在将标头发送到客户端后无法设置标头
- python - 如何在 python PYQT 中使用“ScrollArea”