Home > Back-end >  How to parse integers as command line arguments?
How to parse integers as command line arguments?

Time:12-07

I want to take integers as command line arguments into a shell script and doing basic string manipulations with these integers.

For example:

# POSIX Shell
user@host $ ./script 3 4 1 5
^
| * * *
| * * * *
| *
| * * * * *
------------

user@host $

And some pseudocode to demonstrate, how I would like to achieve this:

# Pseudocode
#!/bin/sh
for arg in $#; do
    echo $((arg * '* '))
done

# Or something similar with a loop ;-)

If someone got an idea that could lead me into the right direction in a pure POSIX Shell like /bin/sh, that would be very nice!

CodePudding user response:

There's a lot of ways to skin this cat. Here's one:

#!/bin/bash
array=( "$@" )

function repeat() { num="${2:-100}"; printf -- "$1%.0s" $(seq 1 $num); printf '\n'; }

arraylength=${#array[@]}
for (( i=0; i<${arraylength}; i   ));
do
   if [[ ${array[$i]} -ge $max ]]; then
        max=${array[$i]}
   fi
   printf '%s' '| '
   repeat '* ' ${array[$i]}
done

repeat '-' $(( $max $max 3 ))

Or doing it in awk:

echo "3 4 1 5" | awk 'function a(b,c){r="";while(c-->0)r=r b;print r}{for(i=1;i<=NF;  i){printf "| ";a("* ",$i);if(m<$i)m=$i}}END{a("-",(m*2) 3)}'

CodePudding user response:

I believe this is the crux of what you're looking for, and should be scrupulously POSIXly compliant, too:

#! /bin/sh

for n; do
  printf '| ';
  i=0;
  while [ $i -lt $n ]; do
    printf '* ';
    i=$(( i   1 ));
  done
  printf '\n';
done
  • Related