rm fails to delete files by wildcard from a script, but works from a shell prompt

前端 未结 6 662
广开言路
广开言路 2021-01-30 19:51

I\'ve run into a really silly problem with a Linux shell script. I want to delete all files with the extension \".bz2\" in a directory. In the script I call

rm \         


        
6条回答
  •  不要未来只要你来
    2021-01-30 20:34

    Just to expand on this a bit, bash has fairly complicated rules for dealing with metacharacters in quotes. In general

    • almost nothing is interpreted in single-quotes:

       echo '$foo/*.c'                  => $foo/*.c
       echo '\\*'                       => \\*
      
    • shell substitution is done inside double quotes, but file metacharacters aren't expanded:

       FOO=hello; echo "$foo/*.c"       => hello/*.c
      
    • everything inside backquotes is passed to the subshell which interprets them. A shell variable that is not exported doesn't get defined in the subshell. So, the first command echoes blank, but the second and third echo "bye":

      BAR=bye echo `echo $BAR`
      BAR=bye; echo `echo $BAR`
      export BAR=bye; echo `echo $BAR`
      

    (And getting this to print the way you want it in SO takes several tries is apparently impossible...)

提交回复
热议问题