我有一些不同的脚本,最终目标是使用以下类型的标记系统和任何给定的命令生成bash代码:
### <!-- BOF HTTPDERRORS --> ###
HTTPDERRORS=()
for OUTPUT in "$(sudo find /|grep error_log)"
do
HTTPDERRORS+=("$OUTPUT")
done
# replace array results with tag
echo "$(echo "$HTTPDERRORS"|sed "s/$/ [HTTPDERRORS]/g")"
### <!-- EOF HTTPDERRORS --> ### >
------
/var/log/httpd/error_log-20150412 [HTTPDERRORS]
/var/log/httpd/error_log-20150405 [HTTPDERRORS]
/var/log/httpd/error_log [HTTPDERRORS]
允许使用下面的python代码解析它:
if "[HTTPDERRORS]" in line:
myhttpderrors = line.split('\n')
for output in myhttpderrors:
httpderrors.append(output)
我使用下面的脚本片段添加命令:
COMMAND=${OPTARG}
### <!-- BOF $TITLE_UPPER --> ### \n
$TITLE_UPPER=()
for OUTPUT in \"\$($COMMAND)\"
do
"$TITLE_UPPER"+=(\"\$OUTPUT\")
done
echo \"\$(echo \"\$$TITLE_UPPER\"|sed \"s/\$/ [$TITLE_UPPER]/g\")\"
### <!-- EOF $TITLE_UPPER --> ### >
" > "$DIR/commands/$TITLE_LOWER.sh"
这适用于简单的命令,如“ls -lha”或“fdisk -l”,其中不涉及任何逻辑,但在添加类似for循环(“-a”添加命令,“ -r“删除”:
./manage_commands.sh -a -t "genchkcfg" -c "for i in $(chkconfig --list | grep 3:off | awk '{print $1}'); do echo -e "\n= $i ="; service $i status; done|grep running)"
GENCHKCFG=()
for OUTPUT in "$(for i in $(chkconfig --list | grep 3:off | awk '{print }'); do echo -e n=)"
do
GENCHKCFG+=("$OUTPUT")
done
echo "$(echo "$GENCHKCFG"|sed "s/$/ [GENCHKCFG]/g")"
### <!-- EOF GENCHKCFG --> ###
产生以下错误:
bash commands/genchkcfg.sh
commands/genchkcfg.sh: command substitution: line 9: syntax error near unexpected token `)'
commands/genchkcfg.sh: command substitution: line 9: `for i in $(chkconfig --list | grep 3:off | awk '{print }'); do echo -e $i)"'
是否有一种更好但又更优雅的方法可以确保像循环这样的语句以及if语句作为单行语言几乎可以保证每次添加都没有错误?