shell携带附件,Linux下的自解压文件诞生了

初衷

windows下有自解压文件,直接双击就能释放文件,并且还能执行释放文件前后要执行的脚本。Linux下我也想要这样的功能,因为我希望直接拷贝一个shell脚本给别人,别人直接运行就能用,而不是一个压缩文件,需要别人解压。

实现

#!/bin/bash

# write header
cat > attachment.sh <<EOF
#!/bin/bash
base64 -d > attachment_test <<EOF
EOF

# write attachment base64 data
(cat <<EOF
#include<stdio.h>

int main(int argc,char *argv[])
{
  int i = 0;
  for (;i<argc;i++) {
    printf("%d:%s\n",i,argv[i]);
  }
	return 0;
}
EOF
) | gcc -s -o /dev/fd/1 -xc - | base64 >> attachment.sh

# write tail
cat >> attachment.sh <<END
EOF
chmod +x attachment_test
./attachment_test 1 2 3 4 5
END

# exec
bash attachment.sh

下面是结果
result:
# ./test.sh
0:./attachment_test
1:1
2:2
3:3
4:4
5:5

执行上述shell脚本会产生如下2个文件,一个是自解压shell脚本,一个是释放的可执行程序。
attachment.sh attachment_test

posted @ 2020-01-09 22:07  janbar  阅读(313)  评论(0编辑  收藏  举报