">" 可以包含在 bash 变量中吗?

030*_*030 2 bash quoting variable

当前方法

sudo awk 'BEGIN{printf "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<hello>\n\t<world>\n";} {print "\t\t",$0}END{printf "\t </world>\n</hello>\n"}' hello > hello2
Run Code Online (Sandbox Code Playgroud)

首选方法不起作用

hello > hello2 想定义为变量以避免代码重复

$CURRENT_TO_OUT=hello > hello2

echo "CP1" $CURRENT_TO_OUT

sudo awk 'BEGIN{printf "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<hello>\n\t<world>\n";} {print "\t\t",$0}END{printf "\t </world>\n</hello>\n"}' $CURRENT_TO_OUT
Run Code Online (Sandbox Code Playgroud)

输出 $CURRENT_TO_OUT:

CP1 hello

jof*_*fel 5

变量扩展后,命令行通常不会重新解释。您需要调用 以eval获取想要的行为。

你实际上有一个XY 问题。为避免代码重复,请改用 shell 函数:

convert_func(){
   echo "CP1 $1" > "$2"
   sudo awk 'BEGIN{printf "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<hello>\n\t<world>\n";} {print "\t\t",$0}END{printf "\t </world>\n</hello>\n"}' "$1" > "$2"
}

convert_func input1 targetfile1
convert_func input2 targetfile2
Run Code Online (Sandbox Code Playgroud)