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"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值