Bash-字符串,命令和转义(哦,我的!) [英] Bash - Strings, Commands and Escaping (oh, my!)
问题描述
我现在正在浪费太多时间,试图弄清这么简单的东西....
I'm wasting so much time right now trying to figure out something so simple....
伪代码(几种语法的混合,抱歉):
pseudo code (mixture of several syntax's, sorry):
cmd1 = "find /my/starting/path -type f | grep -v -f /my/exclude/files"
cmd2 = " nl -ba -s' ' "
cmd3 = " | xargs mv -t /move/here/dir "
echo run_command_and_return_output($cmd1$cmd2)
$cmd1$cmd3 # just this now...
# i don't actually want a function... but the name explains what i want to do
function run_command_and_return_output(){ /* magic */ }
这有效....
this works....
FIND=$(find $LOG_DIR -type f | grep -v -f $EXCLUDE | nl -ba -s' ')
printf "%s\n" "$FIND"
这不是...
NL="nl -ba -s' '"
FIND=$(find $LOG_DIR -type f -mtime +$ARCH_AGE | grep -v -f $EXCLUDE | $NL)
printf "%s\n" "$FIND"
这也不是...
NL='nl -ba -s'\'' '\'' '
这绝对可以,但是:
find /my/starting/path -type f | grep -v -f /my/exclude/files | nl -ba -s' '
或
FIND=$(find $LOG_DIR -type f -mtime +$ARCH_AGE | grep -v -f $EXCLUDE | nl -ba -s' ' )
推荐答案
简写形式:扩展$foo
不带引号的内容通过字符串拆分和glob扩展运行,但不是语法分析.这意味着在不同上下文中使用引号和转义符的字符不会被视为语法,而只会被视为数据.
Short form: Expanding $foo
unquoted runs the content through string-splitting and glob expansion, but not syntactical parsing. This means that characters which would do quoting and escaping in a different context aren't honored as syntax, but are only treated as data.
如果要通过语法分析来运行字符串,请使用eval
,但请注意警告,警告很大,而且影响安全性.
If you want to run a string through syntactical parsing, use eval
-- but mind the caveats, which are large and security-impacting.
更好的方法是使用正确的工具完成工作-在shell数组中构建单个简单命令(而不是管道!),并使用函数作为构造复杂命令的可组合单元. BashFAQ#50 描述了这些工具-并深入讨论了哪种工具合适.什么时候.
Much better is to use the right tools for the job -- building individual simple commands (not pipelines!) in shell arrays, and using functions as the composable unit for constructing complex commands. BashFAQ #50 describes these tools -- and goes into in-depth discussion on which of them is appropriate when.
更具体一点:
nl=( nl -ba -s' ' )
find_output=$(find "$log_dir" -type f -mtime "+$arch_age" | grep -v -f "$exclude" | "${nl[@]}")
printf "%s\n" "$find_output"
...将是正确的,因为它以数组的形式跟踪简单命令nl
.
...would be correct, since it tracks the simple command nl
as an array.
这篇关于Bash-字符串,命令和转义(哦,我的!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!