Search code examples
linuxbashcommand-substitution

Bad Substitution when assigning stat command output to a variable


I have a script which uses find and chgrp/chmod to recursively set certain permissions and group on a directory which is specified in $1

To extract the group of this target directory, I use

mygrp = ${stat -c %G $mydir}

But executed under bash, this generates an error:

${stat -c %G $mydir}: bad substitution

Running the command plainly as

stat -c %G $mydir

Extracts the group correctly, by I can't seem to get it into the mygrp variable.


Solution

  • You should have been doing

    $(stat -c %G "$mydir") 
    

    instead of

    ${stat -c %G $mydir}
    

    You should put $mydir in double quotes given that directory name may be non-standard , say they contain newlines. If the line were

       $(stat -c %G $mydir) 
    

    then :

    $ ./your_script_name "dir
    37190290"
    

    would fail with :

    stat: cannot stat `dir': No such file or directory
    stat: cannot stat `37190290': No such file or directory