Bash - Strings, Commands and Escaping (oh, my!)

前端 未结 1 1453
Happy的楠姐
Happy的楠姐 2020-12-22 06:57

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          


        
相关标签:
1条回答
  • 2020-12-22 07:23

    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.

    If you want to run a string through syntactical parsing, use eval -- but mind the caveats, which are large and security-impacting.

    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.


    To get a bit more concrete:

    nl=( nl -ba -s'  ' )
    find_output=$(find "$log_dir" -type f -mtime "+$arch_age" | grep -v -f "$exclude" | "${nl[@]}")
    printf "%s\n" "$find_output"
    

    ...would be correct, since it tracks the simple command nl as an array.

    0 讨论(0)
提交回复
热议问题