首页 > 解决方案 > 可移植地过滤掉无效的 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==做模式匹配

  1. 那正确吗?
  2. 如何将上述表达式转换为在非 bash 以及 bash shell 中运行?

标签: bashshellshposix

解决方案


例条件构造。每个 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

推荐阅读