I have this bash script which pases a text file and I would like to make it a little simpler and shorter to make it more efficient, does anybody have any ideas on how i can do this?
$vi
function displayHelp
{
echo "Use '-f' to set the file to be used "
echo "Use '-s' to sort the data bya column"
echo "Use '-m' to output the rows which match this expression"
}
function displayColumn
{
columnnumber="$2"
awk '{print $'$columnnumber'}' $1
}
function displayParameter
{
parameter="$3"
columnnumber="$2"
awk -v s=$3 -v c=$2 '$c ~ s { print $0 }' $1
}
while getopts f:s:m:h opt
do
case "$opt" in
h) displayHelp;;
f) filepath="$OPTARG";;
s) column="$OPTARG"
displayColumn $filepath $column
;;
m) searchParam="$OPTARG"
displayParameter $filepath $column $searchParam
;;
esac
done
In
displayColumn(), you’re not using-vvariable passing, but indisplayParameter()you are. You should always use-vinstead of embedding shell variables.Also in
displayParameter()you assign two variables and never use them.You should always quote shell variables when they are expanded. It’s not necessary to quote them on the right hand side of an assignment when they appear alone.
There’s no enforcement that
-fis required, if that’s what you intend. Without supplying it (and its required argument), your script will try to read fromstdin(which may be what you intend).There’s no enforcement that
-mand-sare required. Without both of them being present, the AWK command will output an error message.In general, required arguments should be handled as positional parameters and option flags should be used for options (and their arguments).
Your question is possibly better suited for Code Review.