Search code examples
bashstatsubdirectory

Bash script, commands using subdirectory


I am trying to compare the files in two directories but I am having trouble getting my stat command to work properly, I can get it to work from the command line using the same syntax as I have here.

# Usage: compdir <base_dir> <modified_dir>

    # Handle MODIFIED and REMOVED files
    for i in "${arr1[@]}"
    do
        REMOVED=1
        for j in "${arr2[@]}"
        do
            if [ $i = $j ]; then
                # take time stamps
                dir1="$1" 
                dir2="$2"
                stamp1=stat --format %Y "$i"   <--------- THIS LINE
                stamp2=stat --format %Y "$j"
                if [[ $stamp1 > $stamp2 ]] ; then
                    echo "$j MODIFIED"
                fi
                REMOVED=0
                break
            fi
        done
        if [ $REMOVED -eq 1 ]; then
            echo $i REMOVED
        fi
    done
    # handle NEW files
    for j in "${arr2[@]}"
    do
        NEW=1
        for i in "${arr1[@]}"
        do
            if [ $j = $i ]; then
                NEW=0
                break
            fi
        done
        if [ $NEW -eq 1 ]; then
            echo "$j NEW"
        fi
    done

On the line marked with a <------- and the line below I get the error --format: command not found. I am assuming this is because I am in the base directory and not in the subdirectories. Since the arguments passed are the names of the directories I've tried doing something like "$1/$i" to get the line to work but have had no luck.


Solution

  • You cannot just assign a command to a variable, you have to do it in a subshell using $() or ``. Like here:

    Option 1:

    stamp1=$(stat --format %Y "$i")
    

    Option 2:

    stamp1=`stat --format %Y "$i"`
    

    I personally prefer option 1 (subshell)

    Addendum: As stated in the comment by sp asic (thx), use $() as the backticks are the legacy syntax, see: http://mywiki.wooledge.org/BashFAQ/082