可移植地过滤掉无效的PID

Ram*_*lho 3 bash shell posix sh

我写了一个脚本来获取顶级会话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
Run Code Online (Sandbox Code Playgroud)

代码在 bash 中运行,但无法在 dash 上运行并出现语法错误:

./tspid: 16: ./tspid: Syntax error: "(" unexpected (expecting "then")
Run Code Online (Sandbox Code Playgroud)

我的理解是

if [[ "$1" =~ ^[0-9][1-9]*$ ]];using=~做正则表达式匹配,
if [[ "$1" == [1-9]*([0-9]) ]];using==做模式匹配

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

ogu*_*ail 6

例条件构造。每个 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
Run Code Online (Sandbox Code Playgroud)