ERP - MES Interface - several function

Hi all,

I am a rookie regarding shell script programming, YET!! :slight_smile:

Hence, I have choosen a problem from my bad side of life (my job) and I wil try to solve it by using a shell script and get knowledge concerning shell script programming.

Question: As you can see I have already figured out how to use a function, variables, different standard funtions (if, loops,etc). But I struggeld by using the printf function in order to add blanks to string. If the string which I pass into the function is longer than 40 digits then the printf function has to shorten string to 40 digits. This function works perfectly but if the string is shorter than 40 digits then the printf function has to add blanks until the string has a lenght of 40 digits but this part of my shell script doesn't work :mad: !!! The function adds only ONE blank

#!/bin/bash
fkt_auffuellen()
{
case $1 in
 "C")
   if [ ${#2} -eq $3 ]; then
    value=$2
   elif [ ${#2} -lt $3 ]; then 
    value="$(printf "%-$3s" $2)"
   else
    value="$(printf "%.$3s" $2)"
fi;; 
 "N")
;;
 "D")
;;
esac
}
vorg_nr_t=C
vorg_nr="AUFTRAG005-010010"
vorg_nr_l=40
fkt_auffuellen $vorg_nr_t $vorg_nr $vorg_nr_l
echo $value

if anyone can give an advice it would be great!!!!

Thanks in advance and cold but sunny greetings form BERLIN Area!

Noobie1995

P.S.: I am so sorry for my english it has been a while..........

Hi, try:

echo "$value"
1 Like

Great, it works but you can imagine it brings me to some more questions:

  1. why I have to pass the value variable into ""?
  2. I have extended the code (green lines) and the code brings the previous[incorrect result]?
#!/bin/bash
fkt_auffuellen()
{
case $1 in
 "C")
   if [ ${#2} -eq $3 ]; then
    value=$2
   elif [ ${#2} -lt $3 ]; then 
    value="$(printf "%-$3s" $2)"
   else
    value="$(printf "%.$3s" $2)"
fi;; 
 "N")
;;
 "D")
;;
esac
}
vorg_nr_t=C
vorg_nr="AUFTRAG005-010010"
vorg_nr_l=40
fkt_auffuellen $vorg_nr_t $vorg_nr $vorg_nr_l
vorg_nr="$value"
echo $vorg_nr

Try:

vorg_nr=$value
echo "$vorg_nr"

You do not need the double quotes with the assignment, but you do need them with the echo statement, otherwise the content of the variable will be interpreted by the shell and split into fields using IFS (the input field selector)..

1 Like

And the same rule applies here:

value=$(printf "%-$3s" "$2")

value= is an assignment, no need for quotes.
$2 is an argument (of the printf command), to be quoted.

---------- Post updated at 12:37 PM ---------- Previous update was at 12:27 PM ----------

The exception proves the rule:

if [ ${#2} -eq "$3" ]; then

These are arguments to the [ ] (test) function.
The $3 should be quoted if can be tampered with, e.g. became a * or 1 2 .
Not needed, if your script guarantees a number.
The ${#2} is always a number.

1 Like

Thanks all,

the comments have been very helpful and I can see clearly the problem.

Thanks and have a nice weekend

BR,

Noobie1995