dos2unix Script: How to convert DOS text into Unix text ?

Today we will see a useful script to convert DOS text into Unix text.

The script will take backup of original file before making changes.

And then makes the changes in the original text.

I. dos2unix Script

#!/bin/ksh

fname=$1

echo ${fname}

if [[ ${fname} == "" ]]
then
echo "Usage: dos2unix "
exit
fi

if [[ ! -f ${fname} ]]
then
echo "${fname} does not exist"
exit
fi

cp ${fname} ${fname}.orig

if [[ $? != 0 ]]
then
echo "unable to take backup copy of file to be converted"
exit
fi

tr -d '\r' < ${fname} > ${fname}.conv

if [[ $? != 0 ]]
then
echo "unable to convert file"
exit
fi

mv ${fname}.conv ${fname}

if [[ $? != 0 ]]
then
echo "unable to overwrite original file with converted file. Converted file name is ${fname}.conv "
exit
fi

 

II. Understanding the Script

Lets understand the parts of the script what actually we did above.

a. Show help

If the command ran without any options, it will show:
Usage: dos2unix

fname=$1

echo ${fname}

if [[ ${fname} == "" ]]
then
echo "Usage: dos2unix "
exit
fi

 

b. Check if filename exists or not.

if [[ ! -f ${fname} ]]
then
echo "${fname} does not exist"
exit
fi

 

c. Copy the file in order to take backup.
If copy encountered an error, then update the user.

cp ${fname} ${fname}.orig

if [[ $? != 0 ]]
then
echo "unable to take backup copy of file to be converted"
exit
fi

 

d. Remove the extra characters and create a new file with .conv extension

tr -d '\r' < ${fname} > ${fname}.conv

 

e. In case the last command failed i.e. not able to run tr command, throw an error on the screen.

if [[ $? != 0 ]]
then
echo "unable to convert file"
exit
fi

 

f. Copy the converted file in place of original file.
In case of error while copying, throw an error on screen.

mv ${fname}.conv ${fname}

if [[ $? != 0 ]]
then
echo "unable to overwrite original file with converted file. Converted file name is ${fname}.conv "
exit
fi
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments