0

I am trying to write a bash script that takes 2 inputs: a list of IDs and 2) a directory. The idea is that the script will move a subset of files corresponding to the list of IDs into a a new folder.

#! /usr/bin/bash

LIST_FILE=$(cat ${1}) # List of file IDs (example entry: 1.2345)
PATH=${2}             # directory name   (i.e group_1)


for i in ${LIST_FILE}
        do
        /usr/bin/mv /tmp/project/project_data/data_all/${i}.annotated.gz /tmp/project/project_data/${PATH}/
        done

The script manages to loop ok, however I get the following error for each iteration:

/usr/bin/mv: cannot stat '/tmp/project/project_data/data_all/1.2345'$'\r''.annotated.gz': No such file or directory

It looks like the file name hasn't concatenated properly and I'm not sure why. I've tried researching the problem but I'm also quite new to bash and finding it hard to grasp the concept of the stat error. I appreciate any advice and possible solutions.

Thanks everyone.

Jepson
  • 47
  • 1
  • 6
  • The variable name `PATH` has a very special meaning -- it tells the system where to look for command executables. Using it for anything else will cause trouble (for example, [this](https://stackoverflow.com/questions/52797473/bash-command-not-found-inside-for-loop)). Actually, it's safest to use lower- or mixed-case variable names to avoid conflicts with the many all-caps names with special meanings; see [this](https://stackoverflow.com/questions/673055/correct-bash-and-shell-script-variable-capitalization/673940#673940). – Gordon Davisson Jun 24 '21 at 03:12

1 Answers1

0

I think that the file whose name you pass as the first argument to your script is in dos format instead of unix so you are getting extra \r characters in your file names.

You could change your third line to:

LIST_FILE=$(cat ${1}|tr -d '\r')

Bobby

Bobby Durrett
  • 1,223
  • 12
  • 19
  • True as far as it goes, but one shouldn't be storing lists in strings at all; lists should be stored in _arrays_. `readarray -t list < <(tr -d '\r' <"$1")` will put contents in `"${list[@]}"` (to be later iterated over using `for i in "${list[@]}"` -- the quotes are important) without word-splitting on spaces, expanding globs, or doing any of the other awful, unwanted side effects that one gets with `for i in ${LIST_FILE}`. – Charles Duffy Jun 23 '21 at 23:47
  • ...alternately, one could use just `readarray -t list <"$1"`, and then `for i in "${list[@]}"; do i=${i%$'\r'}; ...; done` to strip the trailing carriage returns off in native bash as they're read. – Charles Duffy Jun 23 '21 at 23:50