蓝天

理解shell的eval命令

看以下两条命令:
[zhangsan@XEN /sys]$ a="ls";b="\$a";c="$b";"$c"
Hey! No command '$a' found, did you mean 'ia'?

[zhangsan@XEN /sys]$ a="ls";b="\$a";c="$b";eval "$c"
block bus class dev devices firmware fs kernel module power

eval命令的作用是再次扫描解释,可多次叠加,如:
[zhangsan@XEN /sys]$ a="ls";b="\$a";c="\$b";eval "$c"
Hey! No command '$a' found, did you mean 'ia'?
[zhangsan@XEN /sys]$ a="ls";b="\$a";c="\$b";eval eval "$c"
block bus class dev devices firmware fs kernel module power

附: 关闭文件描述符函数,并导出该函数给子进程使用
close_all_fd()
{
    # 0, 1, 2, 255
    # compgen -G "/proc/$BASHPID/fd/*
    for fd in $(ls /proc/$$/fd); do
        if test $fd -gt 2; then
            # 关闭文件描述符fd
            eval "exec $fd>&-"
        fi
    done
}
# 导出close_all_fd
export -f close_all_fd
实际应用,可参见:https://github.com/eyjian/libmooon/blob/master/shell/process_monitor.sh

posted on 2018-12-21 13:32  #蓝天  阅读(1064)  评论(0编辑  收藏  举报

导航