使用eval命令创建命令别名

时间:2011-10-25 14:49:35

标签: regex bash eval

对于我的生活,我无法使用bash脚本执行alias命令,将工作站的主机名设置为WOL(Wakeup On Lan)等效命令。我认为必须引用一个我错过的地方的问题。

#!/bin/bash

WOLHosts=`nvram get wol_hosts`

WOLList=($(echo "$WOLHosts" |  grep -o '[A-F0-9]\{2\}:[A-F0-9]\{2\}:[A-F0-9]\{2\}:[A-F0-9]\{2\}:[A-F0-9]\{2\}:[A-F0-9]\{2\}=[^=]*=[0-9]*[.][0-9]*[.][0-9]*[.][0-9]*' ))

if [ "${#WOLList[@]}" -gt 0 ]
then
for Match in ${WOLList[@]}
do
    Command=`echo "$Match" |  sed -r "s/([A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2})=([^=]*)=([0-9]*[.][0-9]*[.][0-9]*[.][0-9]*)/alias \2='\/usr\/sbin\/wol -i \3 \1'/"`
    Name=`echo "$Match" |  sed -r "s/([A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2})=([^=]*)=([0-9]*[.][0-9]*[.][0-9]*[.][0-9]*)/\2/"`
    Com=`echo "$Match" |  sed -r "s/([A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2})=([^=]*)=([0-9]*[.][0-9]*[.][0-9]*[.][0-9]*)/\/usr\/sbin\/wol -i \3 \1/"`
    alias $Name="$Com"
    eval $Command
    echo "$Command"
done
fi

exit 0

以下是我目前通过脚本收到的一些示例数据和输出:

输入(进入WOLHosts):

00:1F:D0:26:72:53=Justin-PC=192.168.1.255 00:16:17:DD:12:7B=Justin-HTPC=192.168.1.255 00:1C:25:BC:C3:85=justinlaptop=192.168.1.255

vi WOecho“$ Command”产生的输出是:

alias Justin-PC ='/ usr / sbin / wol -i 192.168.1.255 00:1F:D0:26:72:53'
别名Justin-HTPC ='/ usr / sbin / wol -i 192.168.1.255 00:16:17:DD:12:7B'
alias justinlaptop ='/ usr / sbin / wol -i 192.168.1.255 00:1C:25:BC:C3:85'

1 个答案:

答案 0 :(得分:2)

由于您似乎将此作为脚本运行,因此您当前的shell将不会收到别名 - 别名将消失,然后驱动脚本的bash进程结束。

尝试:. script.shsource script.sh