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
  • 39,105
  • 12
  • 41
  • 62
kittu
  • 6,112
  • 20
  • 81
  • 157

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
  • 39,105
  • 12
  • 41
  • 62
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
  • 713,503
  • 59
  • 514
  • 593
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
  • 15,702
  • 7
  • 33
  • 75