将 bash 脚本嵌入到另一个 bash 脚本中的正确方法

将 bash 脚本嵌入到另一个 bash 脚本中的正确方法

请建议或更正以下代码,或者如果可能的话使其更简单。

该文件必须嵌入到单个 shell 脚本文件中。

Embedded.sh

#!/bin/bash
echo '#!/bin/bash
read input
while [[ $input -eq Y ]]; do echo hi ; done ' > /tmp/test.sh
chmod ugo+w /tmp/test.sh ; chmod ugo+w /tmp/test.sh ; chmod ugo+x /tmp/test.sh
konsole -e sh /tmp/test.sh
rm /tmp/test.sh

答案1

#!/bin/bash

out=/tmp/script.sh

data='
IyEvYmluL2Jhc2gKcmVhZCBpbnB1dAp3aGlsZSBbWyBcJGlucHV0IC1lcSBZIF1dOyBkbyAj
IG5vdGUgdGhlIGVzY2FwZWQgJCBoZXJlCiAgZWNobyBoaQpkb25lCg=='

base64 -d <<<"$data" >"$out" &&
chmod +x "$out"

对包含的脚本进行编码。这里我使用的是base64编码。对于较大的脚本,请gzip在使用 编码之前压缩数据base64,然后在使用 解码后解压缩base64 -d <<<"$data" | gzip -cd >"$out"

答案2

更具可读性的是定界符:

#!/bin/bash
tempscript="$(mktemp)"
trap 'rm "$tempscript"' EXIT
cat > "$tempscript" << EOF
#!/bin/bash
read input
while [[ \$input -eq Y ]]; do # note the escaped $ here
  echo hi
done
EOF
chmod u+x "$tempscript"
"$tempscript"

相关内容