exec eval source

轉自:http://zhgw01.blog.163.com/blog/static/10414812200912025735381/


eval

eval "translates" a value buried inside a variable, and then runs the command that was buried in there
eval arg1 [arg2 arg3]就是將參數組合起來,並替換其中的變量,這樣得到的結果作爲一條命令進行運行

Code:
for i in 1 2 3
do
   eval myvar="$i"
   echo "$myvar"
done
# this gives 
1
2
3
# why? because there is no metavalue or special meaning to 1 or 2 or 3

Code:
for i in ls df
do
    eval myvar="$i"
    echo "$myvar"
done
# here you get output from the ls command and the df command
如果不使用eval的話,結果就是ls跟df了

   
 另外一個用eval要注意的是:

比如 nn=aa; aa=final; eval dn=\$$nn; echo $dn 會給出final
但是 eval dn=$"$nn";echo $dn給出 aa
eval dn="$"$nn; echo$dn給出final
原因據說是eval對\後面或者“”裏面的字符串不進行擴展,而僅僅只是在其它需要擴展的擴展完成後將“”或者\去掉,最後再作爲命令執行
所以eval dn="$"$nn先擴展出dn="$"aa,再去點""得到dn=$aa,然後將這個作爲命令執行
eval dn=$"$nn"由於“”不進行擴展,而$"xxx"得到的結果是xxx,所以得到dn=$nn作爲命令執行


exec

exec starts another process - BUT - it exits the current process when you do this kind of thing
使用exec,shell就不會調用fork,直接以後面的命令的內容代替當前shell的代碼

Code:
#!/bin/bash

exec echo "leaving this script forever  $0"   # Exit from script here.

# ----------------------------------
# The following line never happens

echo "This echo will never echo."

source

When you run a command in the shell - like another script or a command like ls -
the shell creates a subprocess (called child process). Any environmentvariable that got defined or changed down in the child is LOST FOREVERto the parent process.

However if you source a script (there are two ways) you force thescript to run in the current process. That means environment variablesin the script you ran are NOT LOST.

Code:
# script1
MYVAR="HI there!"
# end script1
Code:
# script2
# first, run script 1
script1
# now is the MYVAR variable set?  No -why? it got set in the child, when the child exited it GOT LOST
echo "MYVAR= $MYVAR"
# now source script1 :: putting a lonesome dot or the command  "source" 
#  in front of the script name have the same effect
. script1
#  . script1 == source script1  these two are the SAME THING
source script1
# now is the MYVAR variable set?  This time we see that MYVAR has a value
echo "MYVAR= $MYVAR"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章