Switching between directories and mkdir/copy dir/file

I was trying to copy the files inside the path /home/user/check/Q1/dir/folder1/expected/n/a1.out1 and a1.out2 and a1.out3 to /home/user/check/Q2/dir/folder1/expected/n/

if n directory is not present at Q2/dir/folder1/expected/ then directory should be created first. And, script follow the config_file to switch between directories and files.

config_File:

cd dir/folder1
test: a1
test: a2
test: a3
cd dir/folder2
test: b1
test: b2
test: b3
cd dir/folder3
test: c1
test: c2
test: c3

Please suggest.

Any attempts / ideas / thoughts from your side?

Hi RudiC,

I have written a code to serve the purpose but looking for a more robust way to deal with it.

$ cat testscript.sh

#!/bin/bash

filename="config_file"


#!/bin/bash

filename="config_file"

destdir="/scratch_b/mannu/check/Q2"

#While loop to read line by line
while IFS= read -r line; do

    if [[ $line == cd* ]] ; then
       cdvar=`echo $line | awk '{print $2}'`
    fi

      echo "echo cdvar: $cdvar"

    if [[ $line == test* ]] ; then

        test=`echo $line | awk -F ':' '{print $2}'|sed -e 's/^[ \t]*//'`

        echo "test : $test"

        destfinal=`echo "$destdir/$cdvar/expected/n"`

        echo "destfinal: $destfinal"

        if [[ ! -e $destfinal ]]; then
           mkdir -p $destfinal
           echo " copy test : $cdvar/expected/n/$test"

           cp $cdvar/expected/n/$test $destdir/$cdvar/expected/n/
        else
           echo " copy test 2: $cdvar/expected/n/$test"

           cp $cdvar/expected/n/$test $destdir/$cdvar/expected/n/
       fi

    fi

done < "$filename"

So you have a working solution? From a high level glimpse at it, I can't see an immediate reason for a failure. So - what's the problem with it? Where is it not robust enough?

Of course, there are some opportunities...

Like if something gonna change in config_file like commenting any test or anything has to be written in the line apart from cd and test. Yes, for now, it's working but I'm looking for the solution/suggestion to make it stable for any future changes in config_file.

For example- config_file include commenting "#" and testfilter - they should not be processed

cd dir/folder1
test: a1
#test: a2
test: a3
testfilter: any node01
test: a4
testfilter:
cd dir/folder2
test: b1
test: b2
test: b3
testfilter: any node01
test: b4
testfilter:
cd dir/folder3
test: c1
test: c2
test: c3

OK; how about - assuming you're in the .../check directory -

while read OP FN REST
  do    case "$OP" in
          \#*)          ;;
          cd)           SD="$FN"
                        TD="Q2/$FN/expected/n"
                        [ -d "$TD" ] ||  mkdir -p "$TD"
                        ;;
          test:)        cp -v Q1/"$SD"/expected/n/"$FN".out[123] "$TD"
                        ;;
          *)            echo "error: OP $OP found but no handler for it."
                        ;;
        esac
  done < config_file

Please add error handling to taste.

1 Like