Soda
Soda

Reputation: 11

How to use a while loop in shell scripting to print on the same line

Hello i am trying to create a shell script in bash that will print a box with a height and width given by the user. so far my code looks like this

#!/bin/bash 
read height
read width
if [ $height -le 2 ];then
echo "error"
fi
if [ $width -le 2 ];then
echo "error"
fi
#this is where i need help
if [ $height -gt 1];then
   if [ $width -gt 1];then
      echo "+"
      counter=$width
      until [ $counter == 0 ]
   do 
      echo "-"
      let counter-=1
   done
fi
fi

Currently it will print each "-" on a new line, how do i print them on the same line? Thank you

Upvotes: 0

Views: 1779

Answers (2)

agc
agc

Reputation: 8406

Less overhead than printf is: echo -n "-"

Example:

for f in {1..10} ; do echo -n - ; done ; echo

Output is 10 hyphens:

----------

Upvotes: 1

Duc Filan
Duc Filan

Reputation: 7157

Try using printf instead:

printf "-"

To pass arguments during running script, using:

$./shell-script-name.sh argument1 argument2 argument3 

Then argument1, argument2 and argument3 becomes $1, $2 and $3 respectively inside your shell script.

In your case:

#!/bin/bash 
height=$1
width=$2
# ... The rest of the file ...

Upvotes: 4

Related Questions