bashのfunction版 rungcc
bashのfunction版 rungccを作ってみた。
オリジナルと比較し ファイルの先頭の#!/home/usr/bin/rungcc ができないだけ。(ここもbash -cオプション等がもう少し研究できれば先にいけそうな気配がある。)
以下を.bashrcに書き込む
function rungcc(){ e=/tmp/___$$;t=$e.c;p="echo -n";echo "#include <stdio.h>">$t;if [ $# = 2 ];then if [ $1 == -e ];then $p "$2">>$t;else $p "int main(){">>$t;a='printf("%';b="\\n\",$2)";case $1 in -m)$p "$2";;-d)$p "${a}d$b";;-f)$p "${a}f$b";;esac>>$t;$p ";}">>$t;fi;else read -rd '' s;$p "$s">>$t;fi;gcc $t -o $e;[ -e $e ]&&($e;rm $e);rm $t; }使い方はオリジナルに準拠
$ rungcc -e 'int main(){printf("全文を書く場合\n");}' ; # include文は不要
全文を書く場合
$ rungcc -m 'printf("メインの省略\n")' ; # main文も不要
メインの省略
$ rungcc -d '1+1' ; #整数の演算を表示
2
$ rungcc -f '1.0/3.0' ; #浮動小数の演算を表示
0.333333
$ echo 'int main(){printf("標準入力から\n");}'|rungcc ; #標準入力からソースを受け取る
標準入力から
展開したソース
functionにするために圧縮かけたので理解のための展開したソースもはっておく。
#!/bin/bash e=/tmp/___$$ # 実行ファイル t=$e.c # ソースファイル p="echo -n" # コマンド圧縮用 echo "#include <stdio.h>">$t if [ $# = 2 ];then # 引数がある場合 if [ $1 == -e ] then $p "$2">>$t else $p "int main(){">>$t a='printf("%' b="\\n\",$2)" case $1 in -m)$p "$2";; -d)$p "${a}d$b";; -f)$p "${a}f$b";; esac>>$t $p ";}">>$t fi else # 標準入力の場合 read -rd '' s; $p "$s">>$t fi cat $t;echo;echo # デバッグ用 gcc $t -o $e [ -e $e ]&&($e;rm $e) rm $t
これをrungcc.shとして保存すると以下のような実行結果になる
$ ./rungcc.sh -e 'int main(){printf("hello,world\n");}'
#include <stdio.h>
int main(){printf("hello,world\n");}
hello,world
$ ./rungcc.sh -m 'printf("hello,world\n")'
#include <stdio.h>
int main(){printf("hello,world\n");}
hello,world
$ ./rungcc.sh -d '1+1'
#include <stdio.h>
int main(){printf("%d\n",1+1);}
2
$ ./rungcc.sh -f '1.0/3.0'
#include <stdio.h>
int main(){printf("%f\n",1.0/3.0);}
0.333333
$ echo 'int main(){printf("hello,world\n");}'|./rungcc.sh
#include <stdio.h>
int main(){printf("hello,world\n");}
hello,world