I'm writing a simple bash script that needs to parse the contents of a file into an array. Entries in the file are "newline" delimited -- so the file would look something like this:


I'd like to parse in the contents and iterate over them. My code currently looks like:

CONTENT=`cat /path/to/text/file.txt`
   echo $PATH
   chmod -R 440 $PATH

This code works great with a file with UNIX line-endings. With a windows formatted text file, however, it chokes miserably. The "echo $PATH" statement produces the correct path, but the chmod fails saying that the file doesn't exist. My knack is that the Windows line-endings aren't getting trimmed, so its trying to chmod a file-path that includes a new line character.

I need to make this thing work regardless of whether the target file was created with Unix or Windows newlines -- but given I am somewhat new to shell scripting I'm not all that sure how to do it.

I appreciate your help!

2 Answers 2


Sounds like you just need to remove the carriage return when processing each line. The real easy way is to use the dos2unix utility, but if your system doesn't have that or you can't get it, you can accomplish similar things with tr, e.g:

echo $PATH | tr -d '\r'

More ideas, such as using sed, are available on the Wikipedia entry.

EDIT: I should point out that $PATH is not a great variable name, since it is undoubtedly set by the environment and other programs may depend on its value. You should consider changing it to something like $CUR_PATH.

  • @Skone: no problemo
    – bjlaub
    Jan 26, 2010 at 0:49

I'd just change the first line of the script:

CONTENT=$(tr -d \\r < /path/to/text/file.txt)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.