理解shell的eval命令

一見發表於2018-12-21

看以下兩條命令:
[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
 

相關文章