在远程主机中运行awk命令失败

时间:2015-06-23 16:06:43

标签: linux awk

我正在运行一个shell脚本来在远程主机上运行awk命令。 awk命令在本地运行正常,但是当远程主机运行失败时(重定向文件为空):

以下是在远程主机上运行的脚本:

host=160.110.235.30
IFM_MOUNT=/opt/insiteone/fuse-mount1
ssh -T root@$host << 'EOF'
awk -v p="$IFM_MOUNT" '{a[NR]=$0}{if(match($0,p)>0){for(i=NR-2;i<=NR+7;i++)d[i]=1}}END{for(i=1;i<=NR;i++)if(!d[i])print a[i]} ' smb.conf >> smb.conf.tmp
EOF

smb.conf.tmp在远程主机中为空!!

本地:

cat smb.conf
[DCCAArchive]
        comment = DCCA Archive File System
        path = /opt/insiteone/fuse-mount/ifm
        read only = No
        case sensitive = yes
        public = yes
        case sensitive = yes
        writeable = yes
        create mask=0777
        guest ok = Yes


[DCCAArchive1]
        comment = DCCA Archive File System
        path = /opt/insiteone/fuse-mount1/ifm
        read only = No
        case sensitive = yes
        public = yes
        case sensitive = yes
        writeable = yes
        create mask=0777
        guest ok = Yes

Running awk locally from shell:
IFM_MOUNT=/opt/insiteone/fuse-mount1
awk -v p="$IFM_MOUNT" '{a[NR]=$0}{if(match($0,p)>0){for(i=NR-2;i<=NR+7;i++)d[i]=1}}END{for(i=1;i<=NR;i++)if(!d[i])print a[i]} ' smb.conf >> smb.conf.tmp

Output (deletes the line matching IFM_MOUNT):
[DCCAArchive]
        comment = DCCA Archive File System
        path = /opt/insiteone/fuse-mount/ifm
        read only = No
        case sensitive = yes
        public = yes
        case sensitive = yes
        writeable = yes
        create mask=0777
        guest ok = Yes

我跟踪this link以便在远程主机上运行awk

1 个答案:

答案 0 :(得分:3)

您选择的引用机制会阻止远程shell看到本地定义的变量IFM_MOUNT。请使用双引号将值插入到字符串中。

host=160.110.235.30
IFM_MOUNT=/opt/insiteone/fuse-mount1
ssh root@$host "awk -v p='$IFM_MOUNT' '
    {a[NR]=\$0}
    {if(match(\$0,p)>0)
      for(i=NR-2;i<=NR+7;i++)
          d[i]=1}
    END{
      for(i=1;i<=NR;i++)if(!d[i])print a[i]} ' smb.conf >> smb.conf.tmp"

注意双引号内的单引号实际上不引用任何内容;所以任何文字的美元符号都需要用反斜杠进行转义。

(我很想对你的Awk脚本进行更实质的重构,但这可能会掩盖这一点。)