Performing string comparison with carriage return in bash

Viewed 8561

Why does the following code fail in bash? Note, I am trying to perform a more complex comparison such as "somestring\r"; this is just a simplified example.

I can confirm that the carriage return "ascii 13" is getting into the script. But I cannot compare against it with a regular string comparison.

The expected result is "1" for a positive match.

Command line:

echo -e "\r" | ./test.sh

Script:

ord() {
   printf '%d' "'$1"
}

read a
echo "1st char: $(ord ${a:0:1})"

left="${a:0:1}"

if [ "$left" = "\r" ]; then
   echo 1
fi

exit 0
1 Answers

The following would illustrate how you can determine if the string contains a carriage return:

read a
if [[ $a =~ $'\r' ]]; then
  echo 1;
fi

Executing it by saying:

echo -e "something\r" | bash foo

would return

1

EDIT: If you want to figure whether the last character of a string contains a carriage return, you could say:

if [[ ${a: -1} = $'\r' ]]; then
  echo 1;
fi
Related