どれが外部ファイルで宣言されているのかわからない
シェルスクリプトでかなりの数の変数を外部ファイルで定義をしているものに出会った時に、どれが外部宣言なのかを調べるために作りました。check.py < sample.shって感じで使います。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# require: python 2.4+ | |
# usage: python sh_declaration_checker.py < sample.sh | |
from re import findall | |
from sys import stdin | |
usedVarlist = set() | |
declaredVarlist = set() | |
for line in stdin: | |
# skip comment line | |
if line.strip()[0:1] == "#": | |
continue | |
# read declared | |
for i in findall("read +[a-zA-Z0-9_]+", line): | |
declaredVarlist.add(i[4:].strip()) | |
# for loop declared | |
for i in findall("for +[a-zA-Z0-9_]+", line): | |
declaredVarlist.add(i[3:].strip()) | |
# normal declared | |
for i in findall("[a-zA-Z0-9_]+=", line): | |
if not i[:-1].isdigit(): | |
declaredVarlist.add(i[:-1]) | |
# used | |
if "$" in line: | |
for i in findall("\${?[a-zA-Z0-9_]+}?", line): | |
if not i[1:].strip("{}").isdigit(): | |
usedVarlist.add(i[1:].strip("{}")) | |
for i in usedVarlist: | |
if i in declaredVarlist: | |
print(i + " is declared in this file.") | |
else: | |
print(i + " is *NOT* declared in this file.") | |
# vim: set ts=4 sw=4 sts=4 expandtab: # |
evalで変数展開して組み合わせて使っている変数には対応していません。
hoge=foo fuga=bar foobar=yes eval echo \$$hoge$fuga # yes