小编Ram*_*lho的帖子

可移植地过滤掉无效的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
Run Code Online (Sandbox Code Playgroud)

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

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

我的理解是

if …

bash shell posix sh

3
推荐指数
1
解决办法
171
查看次数

标签 统计

bash ×1

posix ×1

sh ×1

shell ×1