dos2unix.sh 905 B

12345678910111213141516171819202122232425262728293031
  1. #!/bin/bash
  2. if [[ -z "${1}" ]]; then
  3. echo "No parameter supplied for file to convert" | ts '%Y-%m-%d %H:%M:%S'
  4. exit 1
  5. fi
  6. if [[ ! -f "${1}" ]]; then
  7. echo "File '${1}' does not exist" | ts '%Y-%m-%d %H:%M:%S'
  8. exit 1
  9. fi
  10. # create temp files used during the conversion
  11. TEMP_FILE=$(mktemp /tmp/dos2unixtemp.XXXXXXXXX)
  12. STDOUT_FILE=$(mktemp /tmp/dos2unixstdout.XXXXXXXXX)
  13. # file to convert
  14. SOURCE_FILE="${1}"
  15. # run conversion, creating new temp file
  16. /usr/bin/dos2unix -v -n "${SOURCE_FILE}" "${TEMP_FILE}" > "${STDOUT_FILE}" 2>&1
  17. # if the file required conversion then overwrite (move with force) source file with converted temp file
  18. if ! cat "${STDOUT_FILE}" | grep -q 'Converted 0'; then
  19. echo "Line ending conversion required, moving '${TEMP_FILE}' to '${SOURCE_FILE}'"
  20. mv -f "${TEMP_FILE}" "${SOURCE_FILE}"
  21. fi
  22. # remove temporary files
  23. rm -f "${TEMP_FILE}"
  24. rm -f "${STDOUT_FILE}"