如何测试命令是否为shell保留字?

Edu*_*ero 2 bash shell

我正在写一个bash脚本,我想验证一个字符串是否是一个shell保留字(如if,for,alias,等...).

我怎么能这样做?

Eug*_*sca 6

#!/bin/bash

string="$1"

if [[ $(type "$string" 2>&1) == "$string is a shell"* ]]; then
    echo "Keyword $string is reserved by shell"
fi
Run Code Online (Sandbox Code Playgroud)

  • @Etan Reisner:问题是:`type echo` =>`echo是一个shell builtin`,而`type if` =>`if是一个shell关键字`. (2认同)