bash - 可移植地过滤掉无效的 PID
问题描述
我编写了一个脚本来获取顶级会话 PID,即会话启动器,它可能是 bash、dash、ksh 甚至 systemd 之类的 shell。该脚本可能会获取一个 PID 作为初始参数,但是我需要对其进行过滤以检查它是一个有效的整数而不是类似的东西34fg45
,-5467
而且我不希望它以零开头,例如05467
.
这是脚本的一个片段。
if [ "$1" != "" ]; then
if [[ "$1" == [1-9]*([0-9]) ]]; then <- Check for Integer; error here in non bash shell
if ps -p $1 -o "pid=" >/dev/null 2>&1; then
pid=$1
else
echo "PID $1, no such process." >&2
exit 1
fi
else
echo "Invalid pid." >&2
exit 1
fi
else
pid=$$
fi
代码在 bash 中运行,但无法在 dash 上运行并出现语法错误:
./tspid: 16: ./tspid: Syntax error: "(" unexpected (expecting "then")
我的理解是
if [[ "$1" =~ ^[0-9][1-9]*$ ]];
using=~
做正则表达式匹配,而
if [[ "$1" == [1-9]*([0-9]) ]];
using==
做模式匹配
- 那正确吗?
- 如何将上述表达式转换为在非 bash 以及 bash shell 中运行?
解决方案
用例条件构造。每个 POSIX shell 都有它,与双括号不同,它看起来并不可怕。
# make sure 0-9 is literally 0 to 9
LC_COLLATE=C
# assume set -u is not in effect or $1 is set
case $1 in
('')
# handle empty argument
;;
(0*|*[!0-9]*)
# handle invalid PID (0, 042, 42a, etc.)
;;
(*)
# handle valid PID
;;
esac
# restore LC_COLLATE if necessary
推荐阅读
- python - Python argparse 如何从命令行传递 False?
- laravel - 设置用户和文件夹的权限 - laravel 5.1
- java - 在 Gradle 中使用 ProGuard 收缩普通 Java 库
- sql - 每个变量的单独列
- highcharts - Highcharts 带箭头的弧线
- python - 高效测地线最近邻
- module - 模块中的 Dafny 导出子句
- java - 如何使用 Gremlin 和 Java 查询远程 Apache Tinkerpop 图形数据库?
- c# - 如何使用 c# 将二维数组插入数据库
- android - 最近在firebase数据库结构中添加了一个孩子并且不再工作