0

Bash script:

#!/bin/bash

set -x
parent_folder=$(dirname $PWD)

// read from project-list file and assign to array
mapfile -t arr <project-list.txt

for i in "${arr[@]}"; do
   cd "$parent_folder/$i"
done

Issue: bash: cd: $'/d/workspace/node/notification-service\r': Not a directory. There is \r that is getting added. How to prevent this?

oguz ismail
  • 1
  • 16
  • 47
  • 69
kittu
  • 6,662
  • 21
  • 91
  • 185

3 Answers3

2

If you can't remove them from project-list.txt for some reason (otherwise this question wouldn't make any sense), remove them while expanding arr.

for i in "${arr[@]%$'\r'}"; do
  ...
oguz ismail
  • 1
  • 16
  • 47
  • 69
2

You can change your mapfile statement to remove \r using tr first:

mapfile -t arr < <(tr -d '\r' < project-list.txt)

Afterwards examine array content using:

declare -p arr
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

How to prevent this?

Depends what you mean by to prevent. First of all, I would not put them into project-list.txt. Somewhere must have created this file somehow, and there is rarely a real need to have carriage returns in a file. Prevention would start here.

If for whatever reason this is not possible, you could run the file through dos2unix:

mapfile -t arr <(dos2unix project-list.txt)

or, if git-bash does not support process substitution (I don't have it installed, so I can't try this), you do a

dos2unix <project-list.txt >project-list.sanitized
mapfile -t arr <project-list.sanitized
user1934428
  • 19,864
  • 7
  • 42
  • 87