-1

I am running below commands in a script

move_jobs() {
  cd $JOB_DIR
    for i in `cat $JOBS_FILE`
      do
        if [ `ls | grep -i ^${i}- | wc -l` -gt 0 ]; then
          cd $i
              if  [ ! -d jobs ]; then
                 mkdir jobs && cd .. && mv "${i}"-* "${i}"/jobs/
              else
                  cd .. && mv "${i}"-* "${i}"/jobs/
              fi
          error_handler $?
         fi
      done
}

but it failing as

mv: cannot stat `folder-*': No such file or directory 

Not sure why move command is failing with regular expression

devops
  • 1,121
  • 5
  • 20
  • 50
  • 1
    What is your use-case here? Explain the problem and not show us why your code didn't work! – Inian Jan 11 '19 at 09:05

1 Answers1

4

Your script is overly complicated and has several issues, one of which will be the problem, I guess it's the ls | grep ... part, but to find that out, you should include some debug logging.

  • for i in $(cat ...) loops through words, not lines.
  • Do not parse ls
  • And if you still do, do not ever grep for filenames but include it in your ls call: ls "${i}"-* | wc -l.
  • You do not need to check if a folder exists when the only thing that is different then is that you create it. You can use mkdir -p instead.
  • Jumping around folders in your script makes it almost unreadable, as you need to keep track of all cd commands when reading your script.

You could simply write the following, which I think will do what you want:

xargs -a "$JOBS_FILE" -I{} \
  sh -c "
    mkdir -p '$JOB_DIR/{}/jobs';
    mv '$JOB_DIR/{}-'* '$JOB_DIR/{}/jobs';
 "

or if you need more control:

while IFS= read -r jid; do
    if ls "$JOB_DIR/$jid-"* &>/dev/null; then
        TARGET_DIR="$JOB_DIR/$jid/jobs"
        mkdir -p "$TARGET_DIR"
        mv "$JOB_DIR/$jid-"* "$TARGET_DIR"
        echo "OK"
    else
        echo "No files to move."
    fi
done < "$JOBS_FILE"
pLumo
  • 397
  • 1
  • 13