Frage zur Programierung von Scripten ( wenig code oder übersichtlich ?

Vom einfachen Programm zum fertigen Debian-Paket, Fragen rund um Programmiersprachen, Scripting und Lizenzierung.
Antworten
Benutzeravatar
speefak
Beiträge: 448
Registriert: 27.04.2008 13:54:20

Frage zur Programierung von Scripten ( wenig code oder übersichtlich ?

Beitrag von speefak » 18.11.2018 20:09:46

Ich hab hier nun 2 Script Varianten um die df Ausgabe schöner darzustellen.

In Version 1 hab ich jeden Wert einzeln in die passenden variable geschrieben :

Code: Alles auswählen

#!/bin/bash
# name          : df_mod_v2
# desciption    : show differing FS usage
# autor         : speefak (itoss@gmx.de)
# licence       : (CC) BY-NC-SA
  VERSION=2.1.3
#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
#######################################   define global variables   ########################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------
 ConfigFile=$HOME/.dff.cfg
#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
###########################################   define functions   ###########################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------
usage () {
cat << USAGE
Disk free frontend - display free disk space - version $VERSION
Options are:
 -h, --help      	display help
 -v, --version   	display version
 -m, --monochrome	disable color
 -s, --sumary		print column summary
 -l, --listconfig	show configuration
 -c, --configure 	create new configuration
 -r, --reconfigure 	reconfigure configuration
USAGE
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
configure_dialog () {

# create config file
 ConfigParameterList=$(cat $0 | grep -A50 "configure_dialog () {" | grep "read -e -p \" Enter" | awk -F " " '{print $NF}')

# display Var input prompt and default value, enter/edit value
 df -hT -x tmpfs
 printf "\n"																		# varname in configfile
 read -e -p " Enter local filesystems (main system e.g. /dev/sda1 ...): " 		-i "${FSLocalSystems:-$(df | grep -w "/" | cut -d " " -f1)}" 	FSLocalSystems
 read -e -p " Enter local storage filesystems (storage e.g. sda5 sdb1 /home ...): " 	-i "${FSLocalStorage:-/home}" 					FSLocalStorage
 read -e -p " Enter remote  FSs (e.g. fuse ssh smb ...): " 				-i "${FSRemote:-ssh fuse smb}"  				FSRemote
 read -e -p " Enter sorting column number for FS => local systems: " 			-i "${SortFSColumnSystem:-7}" 					SortFSColumnSystem
 read -e -p " Enter sorting column number for FS => local storage: " 			-i "${SortFSColumnStorage:-7}"  				SortFSColumnStorage
 read -e -p " Enter sorting column number for FS => remote storage: " 			-i "${SortFSColumnRemote:-7}"  					SortFSColumnRemote
 read -e -p " Enter frame color ( default red ): " 					-i "${FrameColor:-1}" 						FrameColor
 read -e -p " Enter column header color (default green): " 				-i "${ColumnHeaderColor:-2}" 					ColumnHeaderColor
 read -e -p " Enter column header color (default green): " 				-i "${ColumnSumaryColor:-3}" 					ColumnSumaryColor
 read -e -p " Enter graph range low % (default 0-59): 0-" 				-i "${GraphThresholdLow:-59}" 					GraphThresholdLow
 read -e -p " Enter graph range mid % (default 60-89): $(($(echo $GraphThresholdLow | cut -d "-" -f2) +1 ))-" -i "${GraphThresholdMid:-89}" 		GraphThresholdMid
 GraphThresholdHigh="100"																GraphThresholdHigh
 GraphRangeLow=$(echo 0-$GraphThresholdLow)
 GraphRangeMid="$(($(echo $GraphThresholdLow | cut -d "-" -f2) +1 ))-$GraphThresholdMid"
 GraphRangeHigh="$(($(echo $GraphThresholdMid | cut -d "-" -f2) +1 ))-100"
 echo	    " Enter graph range high % (default 90-100): $(($(echo $GraphThresholdMid | cut -d "-" -f2) +1 ))-100"
 read -e -p " Enter graph round value $GraphRoundThreshold (default 5): " 		-i "${GraphRoundThreshold:-5}" 					GraphRoundThreshold
 read -e -p " Enter graph color low $GraphRangeLow% (default green): " 			-i "${GraphColorLow:-2}" 					GraphColorLow
 read -e -p " Enter graph color mid $GraphRangeMid% (default yellow): " 		-i "${GraphColorMid:-3}" 					GraphColorMid
 read -e -p " Enter graph color high $GraphRangeHigh% (default red): " 			-i "${GraphColorHigh:-1}" 					GraphColorHigh
 read -e -p " Enter colum sumary output (enable|disable): " 				-i "${ColumnSumaryCalc:-disabled}" 				ColumnSumaryCalc

 # print new Vars
 printf "\n new configuration values: \n\n"
 for i in $ConfigParameterList; do
	echo " $i=\""$(eval echo $(echo "$"$i))\" 
 done

 # check for existing config file
 if [[ -s $ConfigFile  ]]; then
	printf "\n"	
	read -e -p " overwrite existing configuration (y/n) " -i "y" OverwriteConfig
	if [[ $OverwriteConfig == [yY] ]]; then
		rm $ConfigFile		
	else
		sed -i '/Reconfigure=true/d'  $ConfigFile
		sed -i '/CreateNewConfig=true/d'  $ConfigFile 
		printf "\n existing configuration :\n\n"
		cat $ConfigFile
		exit
	fi 
 fi

 # write Vars to config file
 for i in $ConfigParameterList; do
	echo "$i=\""$(eval echo $(echo "$"$i))\" >> $ConfigFile
 done

 printf "\n configuration saved in: $ConfigFile\n"

 $0
 exit
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
load_processing_vars () {
# define colors
 FrameColor=$(tput setaf $FrameColor)
 ColumnHeaderColor=$(tput setaf $ColumnHeaderColor)
 ColumnSumaryColor=$(tput setaf $ColumnSumaryColor)
 GraphColorLow=$(tput setaf $GraphColorLow)
 GraphColorMid=$(tput setaf $GraphColorMid)
 GraphColorHigh=$(tput setaf $GraphColorHigh)
 ResetColor=$(tput sgr0)

 ColumnHeader="System-Device FS-Type Size Used Avail Used% Mountpoint Used-Graph"
 SeperatorLine=$(echo $FrameColor"--------------------------------------------------------------------------------------------------$ResetColor"	)

# define/filter df output
 FSLocalSystemList=$(df -hl --output=source,fstype,size,used,avail,pcent,target | \
			egrep $(echo $FSLocalSystems| tr " " "|") | awk -F " " '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}' | sort -u -k$SortFSColumnSystem )

 FSLocalStorageList=$(df -hl --output=source,fstype,size,used,avail,pcent,target | \
			egrep $(echo $FSLocalStorage| tr " " "|") | awk -F " " '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}' | sort -u -k$SortFSColumnStorage )

 FSRemoteList=$(df -h --output=source,fstype,size,used,avail,pcent,target | \
			egrep $(echo $FSRemote| tr " " "|")  | tr ":" " " | awk -F " " '{print $1,$3,$4,$5,$6,$7,$8,$9}' | sort -u -k$SortFSColumnRemote )
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
calculate_binary_prefix () {
 CalcResult=$(	 if   [[ $(wc -m <<< $1) -gt 13 ]]; then 
			printf $(bc -l <<< $1/2162516033536)P
		 elif [[ $(wc -m <<< $1) -gt 10 ]]; then 
			printf $(bc -l <<< $1/1073741824)T
		 elif [[ $(wc -m <<< $1) -gt 7 ]]; then 
			printf $(bc -l <<< $1/1048576)G
		 elif [[ $(wc -m <<< $1) -gt 4 ]]; then 
			printf $(bc -l <<< $1/1024)M
		 elif [[ $(wc -m <<< $1) -gt 1 ]]; then 
			printf "$1 K"
		 fi ) 

 printf $(echo $CalcResult | sed 's/^\./0./' | cut -c1-4 | sed 's/\.\$//' |sed  's/[ .]*$//' ) 
 printf "$(echo $CalcResult | rev | cut -c1) \n"
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
calculate_values () {
# get calculate values 
 FSLocalSystemListCalc=$(df -l --output=size,used,avail,source,target,fstype | egrep $(echo $FSLocalSystems| tr " " "|") | awk -F " " '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}')
 FSLocalStorageListCalc=$(df -l --output=size,used,avail,source,target,fstype | egrep $( echo $FSLocalStorage| tr " " "|") | awk -F " " '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}')
 FSRemoteListCalc=$(df --output=size,used,avail,source,target,fstype | egrep $(echo $FSRemote| tr " " "|")  | awk -F " " '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}')

 # calculate values 
 FSLocalSystemListSizeRaw=$(bc -l <<< $(echo "$FSLocalSystemListCalc" | awk -F " " '{printf "+" $1 }' | cut -c 2-1000)) 2>/dev/null
 FSLocalSystemListUsedRaw=$(bc -l <<< $(echo "$FSLocalSystemListCalc" | awk -F " " '{printf "+" $2 }' | cut -c 2-1000)) 2>/dev/null
 FSLocalSystemListAvailRaw=$(bc -l <<< $(echo "$FSLocalSystemListCalc" | awk -F " " '{printf "+" $3 }' | cut -c 2-1000)) 2>/dev/null
 FSLocalSystemListSize=$(calculate_binary_prefix "$FSLocalSystemListSizeRaw")
 FSLocalSystemListUsed=$(calculate_binary_prefix "$FSLocalSystemListUsedRaw")
 FSLocalSystemListAvail=$(calculate_binary_prefix "$FSLocalSystemListAvailRaw")
 FSLocalSystemUsedPercent=$(echo $(bc -l <<< $(echo "$FSLocalSystemListUsedRaw / $FSLocalSystemListSizeRaw * 100")) | cut -d "." -f1)%

 FSLocalStorageListSizeRaw=$(bc -l <<< $(echo "$FSLocalStorageListCalc" | awk -F " " '{printf "+" $1 }' | cut -c 2-1000)) 2>/dev/null
 FSLocalStorageListUsedRaw=$(bc -l <<< $(echo "$FSLocalStorageListCalc" | awk -F " " '{printf "+" $2 }' | cut -c 2-1000)) 2>/dev/null
 FSLocalStorageListAvailRaw=$(bc -l <<< $(echo "$FSLocalStorageListCalc" | awk -F " " '{printf "+" $3 }' | cut -c 2-1000)) 2>/dev/null
 FSLocalStorageListSize=$(calculate_binary_prefix "$FSLocalStorageListSizeRaw")
 FSLocalStorageListUsed=$(calculate_binary_prefix "$FSLocalStorageListUsedRaw")
 FSLocalStorageListAvail=$(calculate_binary_prefix "$FSLocalStorageListAvailRaw")
 FSLocalStorageUsedPercent=$(echo $(bc -l <<< $(echo "$FSLocalStorageListUsedRaw / $FSLocalStorageListSizeRaw * 100")) | cut -d "." -f1)%

 FSRemoteListSizeRaw=$(bc -l <<< $(echo "$FSRemoteListCalc" | awk -F " " '{printf "+" $1 }' | cut -c 2-1000)) 2>/dev/null
 FSRemoteListUsedRaw=$(bc -l <<< $(echo "$FSRemoteListCalc" | awk -F " " '{printf "+" $2 }' | cut -c 2-1000)) 2>/dev/null
 FSRemoteListAvailRaw=$(bc -l <<< $(echo "$FSRemoteListCalc" | awk -F " " '{printf "+" $3 }' | cut -c 2-1000)) 2>/dev/null
 FSRemoteListSize=$(calculate_binary_prefix "$FSRemoteListSizeRaw")
 FSRemoteListUsed=$(calculate_binary_prefix "$FSRemoteListUsedRaw")
 FSRemoteListAvail=$(calculate_binary_prefix "$FSRemoteListAvailRaw")
 FSRemoteUsedPercent=$(echo $(bc -l <<< $(echo "$FSRemoteListUsedRaw / $FSRemoteListSizeRaw * 100")) | cut -d "." -f1)%

 SummaryLineLocalSystem="$FSLocalSystemListSize $FSLocalSystemListUsed $FSLocalSystemListAvail $(echo $FSLocalSystemUsedPercent | sed 's/%/%%/') $ResetColor $(print_graph "$FSLocalSystemUsedPercent")"
 SummaryLineLocalStorage="$FSLocalStorageListSize $FSLocalStorageListUsed $FSLocalStorageListAvail $(echo $FSLocalStorageUsedPercent | sed 's/%/%%/') $ResetColor $(print_graph "$FSLocalStorageUsedPercent")"
 SummaryLineRemote="$FSRemoteListSize $FSRemoteListUsed $FSRemoteListAvail $(echo $FSRemoteUsedPercent | sed 's/%/%%/') $ResetColor $(print_graph "$FSRemoteUsedPercent")"
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
monochrome_output () {
 FrameColor=$(tput setaf 7)
 ColumnHeaderColor=$(tput setaf 7)
 ColumnSumaryColor=$(tput setaf 7)
 GraphColorLow=$(tput setaf 7)
 GraphColorMid=$(tput setaf 7)
 GraphColorHigh=$(tput setaf 7)
 SeperatorLine=$(echo $(tput setaf 7)"--------------------------------------------------------------------------------------------------" $(tput sgr0))
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
print_parser_list () {
 echo "$@" | awk -F " " '{printf " %-25s %10s %9s  %6s   %6s   %6s    %11s   %-20s \n", $1, $2, $3, $4, $5, $6, $8, $7}'
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
print_graph_star () {
 for i in `seq 10 10 $GraphValue`; do
	printf "*"
 done
 printf "\n"
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
print_graph () {
 printf $ResetColor
 GraphValue=$(( $(echo "$1" | tr " " "\n" | grep "%" | sed 's/[^0-9]*//g' ) + $GraphRoundThreshold ))
 if   [[ $GraphValue -le $GraphThresholdLow ]]; then
	printf "[$(echo $(echo "$(print_graph_star $GraphValue)" )---------- | cut -c1-10 )" | sed 's/\*/'$GraphColorLow'\*/' | sed 's/\-/'$ResetColor'\-/' && printf $ResetColor]
 elif [[ $GraphValue -le $GraphThresholdMid ]]; then
	printf "[$(echo $(echo "$(print_graph_star $GraphValue)" )---------- | cut -c1-10 )" | sed 's/\*/'$GraphColorMid'\*/' | sed 's/\-/'$ResetColor'\-/' && printf $ResetColor]
 elif [[ $GraphValue -le $(( $GraphThresholdHigh + $GraphRoundThreshold )) ]]; then
	printf "[$(echo $(echo "$(print_graph_star $GraphValue)" )---------- | cut -c1-10 )" | sed 's/\*/'$GraphColorHigh'\*/' | sed 's/\-/'$ResetColor'\-/' && printf $ResetColor]
 fi
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
print_output_line () {  
 SAVEIFS=$IFS
 IFS=$(echo -en "\n\b")
 # proccessing each filesystem input line
 for i in $1 ; do
	print_parser_list "$i $(print_graph $i)"
 done
 IFS=$SAVEIFS
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
#############################################   start script   #############################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
#############################################   check config   #############################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------
 if   [[ -s $ConfigFile  ]] && [[ -z $(cat $ConfigFile | grep "Reconfigure=true\|CreateNewConfig=true") ]]; then
	# read config file
	source $ConfigFile

 elif [[ -s $ConfigFile  ]] && [[ -n $(cat $ConfigFile | grep "Reconfigure=true") ]]; then
	# read config and reconfigure
	source $ConfigFile
 	configure_dialog

 elif [[ ! -s $ConfigFile  ]] || [[ -n $(cat $ConfigFile | grep "CreateNewConfig=true") ]]; then
	# create new config file
	configure_dialog	
 fi
#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
#############################################   check options   ############################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------
load_processing_vars
#-------------------------------------------------------------------------------------------------------------------------------------------------------
 case $1 in
     -[hv])	usage
		exit;;
	-m)	monochrome_output;;
	-s)	calculate_values
		PrintSummary=true;;
	-l) 	cat $ConfigFile
		exit ;;
	-c)	echo "CreateNewConfig=true" >> $ConfigFile
		$0
		exit;;
	-r)	echo "Reconfigure=true" >> $ConfigFile
		$0
		exit;;
	?*)	usage
		exit;;
 esac

#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
#############################################   print output   #############################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------

 printf "$SeperatorLine \n"
 printf "$ColumnHeaderColor" && print_parser_list "$ColumnHeader"
 printf "$SeperatorLine \n"

 printf " MainSystem $FrameColor|$ColumnSumaryColor $(echo $SummaryLineLocalSystem  | awk -F " " '{printf " %32s %7s %8s %9s %38s \n",$1, $2, $3, $4, $6}' ) $ResetColor\n"
 printf "$FrameColor------------+ $ResetColor\n"
 print_output_line "$FSLocalSystemList"
 printf "$SeperatorLine \n"

 printf " Storage FileSystems $FrameColor|$ColumnSumaryColor $(echo $SummaryLineLocalStorage  | awk -F " " '{printf " %23s %7s %8s %9s %38s \n",$1, $2, $3, $4, $6}' ) $ResetColor\n"
 printf "$FrameColor---------------------+$ResetColor\n"
 print_output_line "$FSLocalStorageList"
 printf "$SeperatorLine \n"

 printf " Network shares / Removeable Medium $FrameColor|$ColumnSumaryColor $(echo $SummaryLineRemote  | awk -F " " '{printf " %8s %7s %8s %9s %38s \n",$1, $2, $3, $4, $6}' ) $ResetColor\n"
 printf "$FrameColor------------------------------------+$ResetColor\n"
 print_output_line "$FSRemoteList"
 printf "$SeperatorLine \n"

exit 0
In der Funktion calculate_values sah ich dann, dass ich diesen Variablenhaufen, ggf. mit Schleifen zusammenfassen könnte :

Code: Alles auswählen

#!/bin/bash
# name          : df_mod_v2
# desciption    : show differing FS usage
# autor         : speefak (itoss@gmx.de)
# licence       : (CC) BY-NC-SA
  VERSION=2.1.4
#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
#######################################   define global variables   ########################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------
 ConfigFile=$HOME/.dff.cfg
#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
###########################################   define functions   ###########################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------
usage () {
cat << USAGE
Disk free frontend - display free disk space - version $VERSION
Options are:
 -h, --help      	display help
 -v, --version   	display version
 -m, --monochrome	disable color
 -s, --sumary		print column summary
 -l, --listconfig	show configuration
 -c, --configure 	create new configuration
 -r, --reconfigure 	reconfigure configuration
USAGE
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
configure_dialog () {
 # create config file
 ConfigParameterList=$(cat $0 | grep -A50 "configure_dialog () {" | grep "read -e -p \" Enter" | awk -F " " '{print $NF}')

 # display Var input prompt and default value, enter/edit value
 df -hT -x tmpfs
 printf "\n"																		# varname in configfile
 read -e -p " Enter local filesystems (main system e.g. /dev/sda1 ...): " 		-i "${FSLocalSystems:-$(df | grep -w "/" | cut -d " " -f1)}" 	FSLocalSystems
 read -e -p " Enter local storage filesystems (storage e.g. sda5 sdb1 /home ...): " 	-i "${FSLocalStorage:-/home}" 					FSLocalStorage
 read -e -p " Enter remote  FSs (e.g. fuse ssh smb ...): " 				-i "${FSRemote:-ssh fuse smb}"  				FSRemote
 read -e -p " Enter sorting column number for FS => local systems: " 			-i "${SortFSColumnSystem:-7}" 					SortFSColumnSystem
 read -e -p " Enter sorting column number for FS => local storage: " 			-i "${SortFSColumnStorage:-7}"  				SortFSColumnStorage
 read -e -p " Enter sorting column number for FS => remote storage: " 			-i "${SortFSColumnRemote:-7}"  					SortFSColumnRemote
 read -e -p " Enter frame color ( default red ): " 					-i "${FrameColor:-1}" 						FrameColor
 read -e -p " Enter column header color (default green): " 				-i "${ColumnHeaderColor:-2}" 					ColumnHeaderColor
 read -e -p " Enter column header color (default green): " 				-i "${ColumnSumaryColor:-3}" 					ColumnSumaryColor
 read -e -p " Enter graph range low % (default 0-59): 0-" 				-i "${GraphThresholdLow:-59}" 					GraphThresholdLow
 read -e -p " Enter graph range mid % (default 60-89): $(($(echo $GraphThresholdLow | cut -d "-" -f2) +1 ))-" -i "${GraphThresholdMid:-89}" 		GraphThresholdMid
 GraphThresholdHigh="100"																GraphThresholdHigh
 GraphRangeLow=$(echo 0-$GraphThresholdLow)
 GraphRangeMid="$(($(echo $GraphThresholdLow | cut -d "-" -f2) +1 ))-$GraphThresholdMid"
 GraphRangeHigh="$(($(echo $GraphThresholdMid | cut -d "-" -f2) +1 ))-100"
 echo	    " Enter graph range high % (default 90-100): $(($(echo $GraphThresholdMid | cut -d "-" -f2) +1 ))-100"
 read -e -p " Enter graph round value $GraphRoundThreshold (default 5): " 		-i "${GraphRoundThreshold:-5}" 					GraphRoundThreshold
 read -e -p " Enter graph color low $GraphRangeLow% (default green): " 			-i "${GraphColorLow:-2}" 					GraphColorLow
 read -e -p " Enter graph color mid $GraphRangeMid% (default yellow): " 		-i "${GraphColorMid:-3}" 					GraphColorMid
 read -e -p " Enter graph color high $GraphRangeHigh% (default red): " 			-i "${GraphColorHigh:-1}" 					GraphColorHigh
 read -e -p " Enter colum sumary output (enable|disable): " 				-i "${ColumnSumaryCalc:-disabled}" 				ColumnSumaryCalc

 # print new Vars
 printf "\n new configuration values: \n\n"
 for i in $ConfigParameterList; do
	echo " $i=\""$(eval echo $(echo "$"$i))\" 
 done

 # check for existing config file
 if [[ -s $ConfigFile  ]]; then
	printf "\n"	
	read -e -p " overwrite existing configuration (y/n) " -i "y" OverwriteConfig
	if [[ $OverwriteConfig == [yY] ]]; then
		rm $ConfigFile		
	else
		sed -i '/Reconfigure=true/d'  $ConfigFile
		sed -i '/CreateNewConfig=true/d'  $ConfigFile 
		printf "\n existing configuration :\n\n"
		cat $ConfigFile
		exit
	fi 
 fi

 # write Vars to config file
 for i in $ConfigParameterList; do
	echo "$i=\""$(eval echo $(echo "$"$i))\" >> $ConfigFile
 done

 printf "\n configuration saved in: $ConfigFile\n"

 $0
 exit
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
load_processing_vars () {
 # define colors
 FrameColor=$(tput setaf $FrameColor)
 ColumnHeaderColor=$(tput setaf $ColumnHeaderColor)
 ColumnSumaryColor=$(tput setaf $ColumnSumaryColor)
 GraphColorLow=$(tput setaf $GraphColorLow)
 GraphColorMid=$(tput setaf $GraphColorMid)
 GraphColorHigh=$(tput setaf $GraphColorHigh)
 ResetColor=$(tput sgr0)

 ColumnHeader="System-Device FS-Type Size Used Avail Used% Mountpoint Used-Graph"
 SeperatorLine=$(echo $FrameColor"--------------------------------------------------------------------------------------------------$ResetColor"	)

 # define/filter df output
 FSLocalSystemList=$(df -hl --output=source,fstype,size,used,avail,pcent,target | \
			egrep $(echo $FSLocalSystems| tr " " "|") | awk -F " " '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}' | sort -u -k$SortFSColumnSystem )

 FSLocalStorageList=$(df -hl --output=source,fstype,size,used,avail,pcent,target | \
			egrep $(echo $FSLocalStorage| tr " " "|") | awk -F " " '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}' | sort -u -k$SortFSColumnStorage )

 FSRemoteList=$(df -h --output=source,fstype,size,used,avail,pcent,target | \
			egrep $(echo $FSRemote| tr " " "|")  | tr ":" " " | awk -F " " '{print $1,$3,$4,$5,$6,$7,$8,$9}' | sort -u -k$SortFSColumnRemote )
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
calculate_SI_prefix () {
 CalcResult=$(	 if   [[ $(wc -m <<< $1) -gt 13 ]]; then 
			printf $(bc -l <<< $1/2162516033536)P
		 elif [[ $(wc -m <<< $1) -gt 10 ]]; then 
			printf $(bc -l <<< $1/1073741824)T
		 elif [[ $(wc -m <<< $1) -gt 7 ]]; then 
			printf $(bc -l <<< $1/1048576)G
		 elif [[ $(wc -m <<< $1) -gt 4 ]]; then 
			printf $(bc -l <<< $1/1024)M
		 elif [[ $(wc -m <<< $1) -gt 1 ]]; then 
			printf "$1 K"
		 fi ) 

 printf $(echo $CalcResult | sed 's/^\./0./' | cut -c1-4 | sed 's/\.\$//' |sed  's/[ .]*$//' )
 # append prefix 
 printf "$(echo $CalcResult | rev | cut -c1) \n"
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
calculate_values () {
 # get calculate values 
 FSLocalSystemListCalc=$(df -l --output=size,used,avail,source,target,fstype | egrep $(echo $FSLocalSystems| tr " " "|") | awk -F " " '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}')
 FSLocalStorageListCalc=$(df -l --output=size,used,avail,source,target,fstype | egrep $( echo $FSLocalStorage| tr " " "|") | awk -F " " '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}')
 FSRemoteListCalc=$(df --output=size,used,avail,source,target,fstype | egrep $(echo $FSRemote| tr " " "|")  | awk -F " " '{print $1,$2,$3,$4,$5,$6,$7,$8,$9}')

 # set storage class values 
 for FSClass in FSLocalSystemList FSLocalStorageList FSRemoteList; do
	ColumnCounter=0
	# set column values
	for Column in Size Used Avail; do
		ColumnCounter=$(($ColumnCounter+1))
		# set varnames and calculate values in byte
		eval $(echo "$FSClass""$Column"Raw)=$(bc -l <<< $(eval echo '"'"$""$(eval echo "$FSClass"Calc)"'"' | awk -F " " '{printf "+" $'$ColumnCounter' }' | cut -c 2-1000)) 2>/dev/null
		# calculate SI prefix
		eval $(echo "$FSClass""$Column")=$(calculate_SI_prefix $(eval echo $(echo "$"$(echo "$FSClass""$Column"Raw))))
	done
	# caculate used percent for each filesystemclass
        eval $(echo "$FSClass"UsedPercent)=$(bc -l <<< $(eval echo '"'"$""$(eval echo "$FSClass"UsedRaw)"'"' / '"'"$""$(eval echo "$FSClass"SizeRaw)"'"' '"*"' 100) | cut -d "." -f1)%
 done

 SummaryLineLocalSystem="$FSLocalSystemListSize $FSLocalSystemListUsed $FSLocalSystemListAvail $(echo $FSLocalSystemListUsedPercent | sed 's/%/%%/') $ResetColor $(print_graph "$FSLocalSystemListUsedPercent")"
 SummaryLineLocalStorage="$FSLocalStorageListSize $FSLocalStorageListUsed $FSLocalStorageListAvail $(echo $FSLocalStorageListUsedPercent | sed 's/%/%%/') $ResetColor $(print_graph "$FSLocalStorageListUsedPercent")"
 SummaryLineRemote="$FSRemoteListSize $FSRemoteListUsed $FSRemoteListAvail $(echo $FSRemoteListUsedPercent | sed 's/%/%%/') $ResetColor $(print_graph "$FSRemoteListUsedPercent")"
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
monochrome_output () {
 FrameColor=$(tput setaf 7)
 ColumnHeaderColor=$(tput setaf 7)
 ColumnSumaryColor=$(tput setaf 7)
 GraphColorLow=$(tput setaf 7)
 GraphColorMid=$(tput setaf 7)
 GraphColorHigh=$(tput setaf 7)
 SeperatorLine=$(echo $(tput setaf 7)"--------------------------------------------------------------------------------------------------" $(tput sgr0))
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
print_parser_list () {
 echo "$@" | awk -F " " '{printf " %-25s %10s %9s  %6s   %6s   %6s    %11s   %-20s \n", $1, $2, $3, $4, $5, $6, $8, $7}'
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
print_graph_star () {
 for i in `seq 10 10 $GraphValue`; do
	printf "*"
 done
 printf "\n"
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
print_graph () {
 printf $ResetColor
 GraphValue=$(( $(echo "$1" | tr " " "\n" | grep "%" | sed 's/[^0-9]*//g' ) + $GraphRoundThreshold ))
 if   [[ $GraphValue -le $GraphThresholdLow ]]; then
	printf "[$(echo $(echo "$(print_graph_star $GraphValue)" )---------- | cut -c1-10 )" | sed 's/\*/'$GraphColorLow'\*/' | sed 's/\-/'$ResetColor'\-/' && printf $ResetColor]
 elif [[ $GraphValue -le $GraphThresholdMid ]]; then
	printf "[$(echo $(echo "$(print_graph_star $GraphValue)" )---------- | cut -c1-10 )" | sed 's/\*/'$GraphColorMid'\*/' | sed 's/\-/'$ResetColor'\-/' && printf $ResetColor]
 elif [[ $GraphValue -le $(( $GraphThresholdHigh + $GraphRoundThreshold )) ]]; then
	printf "[$(echo $(echo "$(print_graph_star $GraphValue)" )---------- | cut -c1-10 )" | sed 's/\*/'$GraphColorHigh'\*/' | sed 's/\-/'$ResetColor'\-/' && printf $ResetColor]
 fi
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
print_output_line () {  
 SAVEIFS=$IFS
 IFS=$(echo -en "\n\b")
 # proccessing each filesystem input line
 for i in $1 ; do
	print_parser_list "$i $(print_graph $i)"
 done
 IFS=$SAVEIFS
}
#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
#############################################   start script   #############################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
#############################################   check config   #############################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------
 if   [[ -s $ConfigFile  ]] && [[ -z $(cat $ConfigFile | grep "Reconfigure=true\|CreateNewConfig=true") ]]; then
	# read config file
	source $ConfigFile

 elif [[ -s $ConfigFile  ]] && [[ -n $(cat $ConfigFile | grep "Reconfigure=true") ]]; then
	# read config and reconfigure
	source $ConfigFile
 	configure_dialog

 elif [[ ! -s $ConfigFile  ]] || [[ -n $(cat $ConfigFile | grep "CreateNewConfig=true") ]]; then
	# create new config file
	configure_dialog	
 fi
#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
#############################################   check options   ############################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------
load_processing_vars
#-------------------------------------------------------------------------------------------------------------------------------------------------------
 case $1 in
     -[hv])	usage
		exit;;
	-m)	monochrome_output;;
	-s)	calculate_values
		PrintSummary=true;;
	-l) 	cat $ConfigFile
		exit ;;
	-c)	echo "CreateNewConfig=true" >> $ConfigFile
		$0
		exit;;
	-r)	echo "Reconfigure=true" >> $ConfigFile
		$0
		exit;;
	?*)	usage
		exit;;
 esac

#-------------------------------------------------------------------------------------------------------------------------------------------------------
############################################################################################################
#############################################   print output   #############################################
############################################################################################################
#-------------------------------------------------------------------------------------------------------------------------------------------------------

 printf "$SeperatorLine \n"
 printf "$ColumnHeaderColor" && print_parser_list "$ColumnHeader"
 printf "$SeperatorLine \n"

 printf " MainSystem $FrameColor|$ColumnSumaryColor $(echo $SummaryLineLocalSystem  | awk -F " " '{printf " %32s %7s %8s %9s %38s \n",$1, $2, $3, $4, $6}' ) $ResetColor\n"
 printf "$FrameColor------------+ $ResetColor\n"
 print_output_line "$FSLocalSystemList"
 printf "$SeperatorLine \n"

 printf " Storage FileSystems $FrameColor|$ColumnSumaryColor $(echo $SummaryLineLocalStorage  | awk -F " " '{printf " %23s %7s %8s %9s %38s \n",$1, $2, $3, $4, $6}' ) $ResetColor\n"
 printf "$FrameColor---------------------+$ResetColor\n"
 print_output_line "$FSLocalStorageList"
 printf "$SeperatorLine \n"

 printf " Network shares / Removeable Medium $FrameColor|$ColumnSumaryColor $(echo $SummaryLineRemote  | awk -F " " '{printf " %8s %7s %8s %9s %38s \n",$1, $2, $3, $4, $6}' ) $ResetColor\n"
 printf "$FrameColor------------------------------------+$ResetColor\n"
 print_output_line "$FSRemoteList"
 printf "$SeperatorLine \n"

exit 0
Das ganze hat grad mal 10 Zeilen Code gespart und ist auch noch ca 20 % langsamer

Wie würdet Ihr es machen ?

https://speefak.spdns.de/oss_lifestyle/ ... nd-script/
Zuletzt geändert von speefak am 20.11.2018 18:38:49, insgesamt 1-mal geändert.

Benutzeravatar
MSfree
Beiträge: 10741
Registriert: 25.09.2007 19:59:30

Re: Frage zur Programierung von Scripten ( wenig code oder übersichtlich ?

Beitrag von MSfree » 19.11.2018 08:52:12

Keep It Small and Simple :wink:
Oder auf deutsch:
Warum einfach, wenn man es auch kompliziert machen kann.

Ich finde jedenfalls die Ausgabe von

Code: Alles auswählen

df -x devtmpfs -x tmpfs -m
deutlich übersichtlicher als das, was dein Skript produziert.

df braucht auch keine Konfigurationsdatei, die im Zweifelsfall veraltet ist, z.B. wenn man weiteren Plattenplatz mountet. Der erste Versuch mit deinem Skript auf meinem Rechner hat jedenfalls meine zweite Platte nicht angezeigt, bis ich dann mal in die Konfigurationsdatei geschaut habe.

Letzten Endes hätte es ein apt-get install pydf auch getan, statt das Rad neu zu erfinden. :mrgreen:

Aber immerhin hast du gezeigt, daß du dich mit dem Syntax von bash, awk, cat, grep, sed auskennst :THX:

Benutzeravatar
speefak
Beiträge: 448
Registriert: 27.04.2008 13:54:20

Re: Frage zur Programierung von Scripten ( wenig code oder übersichtlich ?

Beitrag von speefak » 19.11.2018 09:43:43

pydf kannte ich noch gar nicht. discus wäre noch eine andere Möglichkeit. Die Configdatei wollte ich ja haben um nicht immer wieder die gleichen Parameter eingeben zu müssen, bzw default Parameter festzulegen. Eine Auflistung der Summe für Speicherplatz eine Gerätegruppe zeigt keines der bislang genannten Programme an. pydf rechnet gänzlich ohne die reservierten Blöcke. im Manual stand so auch nichts.

Zur eigentlichen Frage : Lieber Schleifen oder Variablenkaskaden ? Letzteres wäre einfacher zu erstellen ( die syntax und das quoten verwirrt mit unter ), Ersteres dafür weniger Code :?:

in dem Sinne Danke für die Blumen ;)

rodney
Beiträge: 334
Registriert: 09.12.2016 04:15:59

Re: Frage zur Programierung von Scripten ( wenig code oder übersichtlich ?

Beitrag von rodney » 22.11.2018 01:10:34

Hat jetzt eigentlich nichts mit deiner Fragestellung zu tun, jedoch gefallen mir persoenlich 2 Dinge nicht.

Der Code ist zumindest fuer mich schlecht lesbar (ueberlange Kommentartrenner, Einrueckung folgt keinem Muster), was jedoch der Funktion keinen Abbruch tut.

Deine Funktion usage gibt neben den Kurzoptionen (-o) auch Langoptionen (--option) an, welche jedoch mit Ausnahme von --help nicht funktionieren.

Benutzeravatar
speefak
Beiträge: 448
Registriert: 27.04.2008 13:54:20

Re: Frage zur Programierung von Scripten ( wenig code oder übersichtlich ?

Beitrag von speefak » 22.11.2018 16:36:35

Hat jetzt eigentlich nichts mit deiner Fragestellung zu tun, jedoch gefallen mir persoenlich 2 Dinge nicht.

Der Code ist zumindest fuer mich schlecht lesbar (ueberlange Kommentartrenner, Einrueckung folgt keinem Muster), was jedoch der Funktion keinen Abbruch tut.
=> wie meinst du das ? Die 3 Zeiligen Scriptbereichtstrenner oder #---- .... ---- ? ( hier vllt übertrieben aber bei einigen hundert Zeilen Script fällt es besser auf )

Deine Funktion usage gibt neben den Kurzoptionen (-o) auch Langoptionen (--option) an, welche jedoch mit Ausnahme von --help nicht funktionieren.
=> Stimmt 8O

rodney
Beiträge: 334
Registriert: 09.12.2016 04:15:59

Re: Frage zur Programierung von Scripten ( wenig code oder übersichtlich ?

Beitrag von rodney » 22.11.2018 17:58:54

=> wie meinst du das ? Die 3 Zeiligen Scriptbereichtstrenner oder #---- .... ---- ? ( hier vllt übertrieben aber bei einigen hundert Zeilen Script fällt es besser auf )
Die bei dir 3-zeiligen Scriptbereichstrenner (153 Zeichen lang) sind bei dir 3-zeilig, bei anderen vielleicht nur eine halbe Zeile oder mehr als 3 Zeilen lang. Zudem umschliessen diese Scriptbereichstrenner 3-zeilige Kommentarbloecke, wovon in der mittleren der eigentliche Kommentar steht. Diese sind fuer sich genommen schon mehr als auffaellig und benoetigen meiner Meinung nach nicht auch noch 109 Zeichen lange Scriptbereichstrenner.

Mit den Einrueckungen meinte ich folgende Beispiele (ueberlange Scriptbereichstrenner/Kommentarzeilen von mir gekuerzt):

Code: Alles auswählen

###########################################################
#---------------------------------------------------------------------------------
 ConfigFile=$HOME/.dff.cfg
#---------------------------------------------------------------------------------
Hier wird um ein Zeichen eingeruegt (warum erschliesst sich mir nicht)

Code: Alles auswählen

 # print new Vars
 printf "\n new configuration values: \n\n"
 for i in $ConfigParameterList; do
	echo " $i=\""$(eval echo $(echo "$"$i))\" 
 done
Hier ist die erste Einrueckung (warum eingerueckt) 1 Zeichen und die Einrueckung innerhalb der for-Schleife 7 Zeichen

Code: Alles auswählen

 # set storage class values 
 for FSClass in FSLocalSystemList FSLocalStorageList FSRemoteList; do
	ColumnCounter=0
	# set column values
	for Column in Size Used Avail; do
		ColumnCounter=$(($ColumnCounter+1))
		# set varnames and calculate values in byte
		eval $(echo "$FSClass""$Column"Raw)=$(bc -l <<< $(eval echo '"'"$""$(eval echo "$FSClass"Calc)"'"' | awk -F " " '{printf "+" $'$ColumnCounter' }' | cut -c 2-1000)) 2>/dev/null
		# calculate SI prefix
		eval $(echo "$FSClass""$Column")=$(calculate_SI_prefix $(eval echo $(echo "$"$(echo "$FSClass""$Column"Raw))))
	done
	# caculate used percent for each filesystemclass
        eval $(echo "$FSClass"UsedPercent)=$(bc -l <<< $(eval echo '"'"$""$(eval echo "$FSClass"UsedRaw)"'"' / '"'"$""$(eval echo "$FSClass"SizeRaw)"'"' '"*"' 100) | cut -d "." -f1)%
 done
Die erste Einrueckung ist hat Zeichen (Space), die zweite Einrueckung 8 Zeichen (Tab) und die dritte Einrueckung 16 Zeichen (2x Tab). Zudem ist ab "# caculate used percent for each filesystemclass ein Einrueckung zuviel.

Das Ganze (Lesbarkeit von Code) ist hier im Thread aber Offtopic, wobei mich da schon auch die Meinungen anderer interessieren wuerde.

Benutzeravatar
speefak
Beiträge: 448
Registriert: 27.04.2008 13:54:20

Re: Frage zur Programierung von Scripten ( wenig code oder übersichtlich ?

Beitrag von speefak » 22.11.2018 19:38:09

Ok 8) - das Formatierungschaos liegt wahrscheinlich an der Auflösung bei mir ( gedit, volle Monitorbreite 1920 px )

thx 4 info ;)

Benno007
Beiträge: 111
Registriert: 26.01.2016 19:25:05

Re: Frage zur Programierung von Scripten ( wenig code oder übersichtlich ?

Beitrag von Benno007 » 23.11.2018 01:07:05

Die Configdatei wollte ich ja haben um nicht immer wieder die gleichen Parameter eingeben zu müssen, bzw default Parameter festzulegen.
Dafür gibt es ja zum Abspeichern Alias. Reicht dir das nicht?

Benutzeravatar
speefak
Beiträge: 448
Registriert: 27.04.2008 13:54:20

Re: Frage zur Programierung von Scripten ( wenig code oder übersichtlich ?

Beitrag von speefak » 23.11.2018 12:48:12

Könnte man auch nutzen, nur dann sind Konfigs von Programmen in der alias Datei - das trenne ich lieber.

Aber zurück zum Topic : Lieber komplizierter verschachtelter Syntax oder alles nachvollziehbarer als Variable ?

Antworten