Write a shell script to print a diamond figure [cl

2019-03-07 04:38发布

This is homework, didn't mean to trick anybody, but I didn't specify that in my original post.

Write a shell script to print the following figure (Do not hardcode).

http://cl.ly/1K0C1b2x3W2N3o3m1Y2y

标签: bash shell
1条回答
我想做一个坏孩纸
2楼-- · 2019-03-07 05:42

On the one hand, I don't like to just give out an answer. On the other hand, I think I've made this sufficiently convoluted that, perhaps, there is some educational value in trying to figure out how it works. Good luck!

#!/bin/sh 

while i=$( expr ${i-0} ${op-+} 1 ); do
    j=$i
    t=$( expr 2 \* $i - 1 )
    printf %$( expr \( $( expr 2 \* ${1-6} - 1 ) - $t \) / 2 )s
    while test $(( j-- )) -gt 0; do printf '* '; done
    echo
    test $i = ${1-6} && op=-
done

And here's a nice variant:

#!/bin/sh

while i=$( expr ${i-0} ${op-+} 1 ); do
    printf %$( expr $(( 2 * $(( ${1-6} - $i )) )) / 2 )s
    printf \*%$(( $i - 1 ))s | sed 's/ / */g'
    test $i = ${1-6} && op=-
done
查看更多
登录 后发表回答