Shell script for formatting long lines

Time:2021-6-20

Long time no update, long time no script
Think it’s time to go on with the script

#14 Formatting Long Lines


#!/bin/sh
# A version of fmt, using nroff. Adds two useful flags: -w X for line width
#  and -h to enable hyphenation for better fills.
while getopts "hw:" opt; do
 case $opt in
  h) hyph=1        ;;
  w) width="$OPTARG"   ;;
 esac
done
shift $(($OPTIND - 1))
nroff << EOF
.ll ${width:-72}
.na
.hy ${hyph:-0}
.pl 1
$(cat "[email protected]")
EOF
exit 0

The above script is used to format the output software
We mainly use getops to get the processing parameters
The unified format of our command line is as follows:

 command -options parameters 

  Getopts statement. The format of the statement is:
getopts option_string variable
Options_ String contains a valid single character option. If the getopts command finds a hyphen on the command line,
Then it will use the character after the hyphen with the option_ String. If there is a match, set the value of variable to this option.
If there is no match, the variable is set to?. When getopts finds that there is no character after the hyphen, it will return a non-zero status value.
Shell program can use the return value of getopts to establish a loop.

Sometimes there is a value in the option, which is also supported by the getopts command. At this time, you need to select options_ Add a colon after the option letter in string. When the getopts command finds a colon, it reads the value from the command line after the option. If the value exists, it will be stored in a special variable optarget. If the value does not exist, the getopts command stores a question mark in optarget and displays a message on the standard error output.
————
optstring   Option string, which will be matched one by one
varname     Successful options for each match
arg         Parameter list. When it is not written, it will take the command line parameter list

$OPTIND     The special variable, option index, will be incremented one by one with an initial value of 1
$OPTARG     Special variables, option argument, have different values in different cases
————

Shift is used to reallocate the location parameters. In fact, it moves the parameters to the left by one position, such as $1 < — $2 and $2 < — $3. The old $1 will be deleted.

————

Script interpretation
shift $(($OPTIND – 1))   Will make [email protected] the last parameter, which is the file name.
${ width:-72 },${ hyph:-0 }Used to define the default value.
Nroff is rarely used now. Looking up the data, it is found that it is used to format the text file into the form required by the line printer or terminal screen.

I feel that this script is not very useful. Linux has ready-made commands to complete this function
He’s FMT.