201702 月发表在 分享

20在 shell 中测试 C 语言表达式用的 bash 脚本

#!/bin/bash
if [ ! "$1" ]; then
    echo "usage: $0 <EXPRESSION>"
    exit
fi
DISPLAY_FILE=display-const-`date +%H%M%S`
gcc -o /tmp/$DISPLAY_FILE -x c - <<EOF
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/signal.h>
int main() {
    int i = 0;
    printf("%s = %d\\n", "$1", (int)($1));
    return 0;
}
EOF
if [ "$?" = "0" ]; then
    /tmp/$DISPLAY_FILE
    rm /tmp/$DISPLAY_FILE
fi

这个脚本的用法非常简单:

zyxwvu@kurumi:~$ chmod +x ./ceval
zyxwvu@kurumi:~$ ./ceval
usage: ./ceval <EXPRESSION>
zyxwvu@kurumi:~$ ./ceval SIGINT
SIGINT = 2
zyxwvu@kurumi:~$ ./ceval AF_INET6
AF_INET6 = 10
zyxwvu@kurumi:~$ ./ceval "i = 3, i++"
i = 3, i++ = 3
zyxwvu@kurumi:~$ ceval "srandom(time(NULL)), random()"
srandom(time(NULL)), random() = 289071694
zyxwvu
UNDER CONSTRUCTION