複雑な変数コンテンツを手動で作成

複雑な変数コンテンツを手動で作成

動的にシェルスクリプトを生成し、実行のためにリモートサーバーに送信します。システムが実行しようとしている複数行、一重引用符、二重引用符、その他の特殊文字を含むファイルの内容を変数に挿入しようとする場合を除いて、すべてがうまく機能します。

例:

my_script=$(cat some script.sh)

cont=$(cat some_template_with_special_chars.sh)
var='the_var_name_to_inject'
kv="$var=$file_contents"

script_to_send=$kv$my_script

sh -t -t -i key usr@ip "$script_to_send"

some_template_with_special_chars.shの内容が単純なテキストであれば動作しますが、複数行と特殊文字がある場合は機能しません。別の問題は、二重引用符を使用してもスペースが失われることです。

ベストアンサー1

「printf」を使用して文字列をエスケープします。

私が正しく理解したら、スクリプトファイルに関連付ける変数割り当てステートメントを生成し、すべてがシェルで実行されます。

この場合、以下を提案します。

#!/bin/bash

my_script=$(<somescript.sh)

cont=$(<file)
var='xx'

# This will escape the string in $cont, and store it in $kv
printf -v kv "$var=%q" "$cont"

script_to_send="$kv
$my_script"

# sh -c used for testing here
sh -c "$script_to_send"

例:

somescript.sh家庭

echo "This is the value of xx:"
echo "$xx"
echo 'Script terminated'

そしてfile包含

aa
bb"
'cc
dd

出力:

This is the value of xx:
aa
bb"
'cc
dd
Script terminated

おすすめ記事