Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash ? appears when array is created from readarray but not manually declared

Tags:

arrays

bash

I have a file (my_ID_file) of IDs, one ID per line, no other excess white white spaces. it was created from using the cut command form another file. the file looks like 101 lines of this...

PA10 
PA102 
PA103 
PA105  
PA107 
PA109 

I am trying to use these IDs in a for loop to create a directory structure. so I use the readarray function as such to create the array...

readarray TIDs < my_ID_file

and then use a for loop as such to create the directory structure...

for T in "${TIDs[@]}"
do
mkdir "$T"_folder
done

this produces directories named....

PA10?_folder
PA102?_folder 
PA103?_folder 
PA105?_folder 
PA107?_folder 
PA109?_folder

If however I declare the array manually like....

TIDs=(PA10 PA102 PA103 PA105 PA107 PA109)

and then run the for loop I get the correct directory structure produced like....

PA10_folder
PA102_folder 
PA103_folder 
PA105_folder 
PA107_folder 
PA109_folder

Where are these question marks coming from? how can i declare arrays from files like this without having this question mark appearing in subsequent use of the array?

Thanks

like image 391
Tom Smith Avatar asked Mar 02 '14 18:03

Tom Smith


1 Answers

Your text file has DOS-style line endings. The "?" appear because the carriage returns would mess up ls output. Try od -c my_ID_file

Solution: dos2unix my_ID_file

take #2: readarray does not remove the line's newline by default. You really want

readarray -t TIDs < my_ID_file

reference: http://www.gnu.org/software/bash/manual/bashref.html#index-mapfile

like image 87
glenn jackman Avatar answered Oct 08 '22 06:10

glenn jackman