0

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

3
  • 1
    Use printf "%s" "+" etc to print without a newline. Or optionally omit the format string since you're only printing a single character. You'll also need to use loops properly. It could be for ((i = 0; i < height; i++); do for ((j = 0; j < width; j++)); do ...; done; printf '\n'; done Commented Oct 4, 2017 at 1:00
  • sorry to clarify my box will be empty on the inside, but with | as the character to make the length part of the box. Commented Oct 4, 2017 at 1:09
  • It's a good idea to show what you want as the output in the question — show the input (the height and width you enter) and the corresponding output. A blank interior makes it easier — you can persuade printf to generate spaces. It is harder to make it produce a different fill character. Commented Oct 4, 2017 at 2:55

2 Answers 2

4

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 ...
Sign up to request clarification or add additional context in comments.

8 Comments

I agree this is part of the answer. The code looks like it needs help with the loops too.
they might i am new to shell scripting and this is our first assignment for it. so far a while loop seemed the best way to do it. also echo -n '-' ended up working as well.
follow up question, if i wanted the input to be entered in the command line instead of during the script how would i read and assign them height and width? thank you again
so to clarify if i just put height (newline) width, when launching $./shell-script-name.sh 10 5 this will set height to 10 and width to 5?
Inside your shell content, you have to assign height=$1 and then width=$2 before using height and width
|
1

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

Example:

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

Output is 10 hyphens:

----------

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.