if 语句中的 Bash 变量替换

问题描述 投票:0回答:1

我有以下我无法控制的 bash 脚本:

set -x
echo "$CMD"
if ${CMD}; then
  echo "Success"
fi

我正在尝试运行以下命令:

bash -c "echo first && echo second"
。我如何将其传递给
CMD
,有什么想法吗?我希望它能与以下内容一起使用:

❯ env CMD='bash -c "echo first && echo second"' bash magic.sh
+ echo 'bash -c "echo first && echo second"'
bash -c "echo first && echo second"
+ bash -c '"echo' first '&&' echo 'second"'
first: -c: line 1: unexpected EOF while looking for matching `"'

但似乎变量替换不允许这样做,因为参数被引用了。

bash variables substitution quoting
1个回答
0
投票
Bash/001> cat test01.sh 
set -x
echo "$CMD"
if ${CMD}; then
  echo "Success"
fi
Bash/001> export CMD='echo -e "first\nsecond"'
Bash/001> ./test01.sh
++ echo 'echo -e "first\nsecond"'
echo -e "first\nsecond"
++ echo -e '"first\nsecond"'
"first
second"
++ echo Success
Success
© www.soinside.com 2019 - 2024. All rights reserved.