Thanks,
In fact I have managed to find a easier solution to display my [ok] at the end of the line.
First I have realized that when the script is executed, it's starting displaying lines at the very beginning of the console and not just after the user's prompt.
Then, instead of trying to figure out how to calculate the lengh, i have realize that whatever the console is resized or full screen, still there are 80 columns available.
So, I only have to create a line which at the end, display my [ok].
I have achieve this with this code :
Note that here $1 is a parameter of a function which accept a command as first parameter, the $2 is also a paramter in case the command $1 is piped with a second command $2
Code:
disp (){
str="Executing :"
str2=$1" "
if ! [ "$2" = "" ]; then
str2=$str2"| "$2" "
fi
str3=$str$str2
strl=${#str3}
let ll=72-$strl
o=""
for i in `seq 0 $ll`;
do
o=$o"."
done
echo -n $str2$o
if ! [ "$2" = "" ]; then
res="$($1 | $2 2>&1)"
else
res="$($1 2>&1)"
fi
err=$?
echo "$res" >> $OUTFILE
if ! [ $err = 1 ]; then
echo " [OK]"
else
echo "[ERROR]"
echo "La commande a retournée l'erreur suivante: "
echo $res
fi
}
- Basically, I build a first string that concatenate the 'header' then the command name
- Then for [ok] and [error] I know that I will need 7 characters but to make thing simplier, the string [ok] will have the same size as [error] (7 characters] by adding spaces to the [ok] string)
- Then a little calculation to know how many charaters there are between the lenght of the header minus the lengh of the result string minus the console columns lenght. It gives 72 because : 72 + 7 (lenght of the result code (" [OK]" or "[ERROR]")) -1 to avoid the carriage return
- Then I build a string with the header, the command, and some dot
- Then execute the command
- Display the result at the end
I can put the result code after the initial string using echo -n which does not do a carriage return.
The command are executed and their stderr code is evaluted to display the result string
An important thing is when you execute a command using $z=$(<command>)
use
with quotes
and
also with quotes
By this way, the resultat will have proper carriage return. If not, then the command will output a single string with no carriage return
Maybe it is not the best code for that but it is simple to use and fit my needs.
If you have a better approach then feel free to post your code or suggestions.