我有一个非常庞大的脚本(其中包含大约4000行代码)。这是其中的一部分:
#!/bin/bash
. ./functions > /dev/null 2>&1
some_function(){
while true
do
CHOICE=$(whiptail --menu "\n\n\n\n\n\n\n\n" --title "Tools" --nocancel $window 20 \
"1" "Option1" \
"2" "Option2" \
"3" "Option3" 3>&1 1>&2 2>&3)
case $CHOICE in
1)echo $1 $2 $3;;
2)echo $2 $1 $3;;
3)echo $3 $2 $1;;
esac
done
}
while true; do
arr=()
for ((n=1; n<=$node_num; n++))
do
node+=($n NODE$n)
done
OPTION=$(whiptail --menu "\n\n\n\nPlease choose:\n\n\n" --title "tools" $window 20 "${node[@]}" \
case $OPTION in
1) some_function 1 2 3 ;;
2) some_function 2 1 3 ;;
3) some_function 3 1 2 ;;
esac
done
我想记录脚本中执行的命令。
目前为止我尝试过的是:
#!/bin/bash -x
--> this will log all the output , but will also "spam" the logs with unneeded information like variable values etc. However this seems to be the best way so far...- I have tried
#!/bin/bash -i
, enabling history with set -o history . The disadvantage of this is it will log everything . When I call the function file for example it will log every single line as if it was executed . I have tried creating a log function :
logthis(){ ## print the command to the logfile echo "$(date) $@" >> $historyfile ## run the command and redirect it's error output ## to the logfile eval "$@" 2>> $historyfile }
This seems to work most of the time. But when I do, for example:
case $OPTION in 1) logthis "some_function 1 2 3" ;; 2) some_function 2 1 3 ;; 3) some_function 3 1 2 ;; esac
无法正常工作,因为我会丢失参数1、2、3。
你有其他想法在bash脚本中实现优雅的日志系统吗?
set -x
和set +x
来根据需要进行启用和禁用;这是选项 1 的更细粒度版本。 - chepner