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

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