[英]echo command behaviour issue in bash
command="echo 'hello world' > file.txt";
$command;
And I'm expecting that it will write the "hello world" text to file.txt, But it prints the whole string as, 我期望它将“ hello world”文本写入file.txt,但是它将整个字符串打印为:
'hello world' > file.txt
What wrongs with my code? 我的代码有什么错误?
After a variable is replaced, the result is only scanned for word splitting and wildcard expansion. 替换变量后,仅扫描结果以进行单词拆分和通配符扩展。 Other special shell characters, such as quotes and redirection, are not processed.
其他特殊的Shell字符(例如引号和重定向)不会被处理。 You need to use
eval
to reprocess it completely: 您需要使用
eval
对其进行完全重新处理:
eval "$command"
You cannot store full command line in variables and execute like this. 您不能将完整的命令行存储在变量中并像这样执行。
Using this will work but is dangerous if command line is coming from users or from an external source: 使用此功能将有效,但如果命令行来自用户或来自外部来源, 则很危险 :
bash -c "$command"
Safe approach is to store command in BASH array: 安全的方法是将命令存储在BASH数组中:
command=(echo 'hello world')
And execute it like this: 并像这样执行它:
"${command[@]}" > file.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.