Bash 函数重复某些字符

Bash 函数重复某些字符

我有以下功能,但如果我有 5 个、6 个等,它是重复的且不可扩展。

append_footnote(){
  file=$1
  if [ "$#" -ge 2 ];then 
    depth=$2
    if [ $depth -eq 1 ];then
      echo '<span style="float: footnote;"><a href="../index.html#toc">Go to TOC</a></span>' >> "$file"
    elif [ $depth -eq 2 ];then
      echo '<span style="float: footnote;"><a href="../../index.html#toc">Go to TOC</a></span>' >> "$file"
    elif [ $depth -eq 3 ];then
      echo '<span style="float: footnote;"><a href="../../../index.html#toc">Go to TOC</a></span>' >> "$file"
    elif [ $depth -eq 4 ];then
      echo '<span style="float: footnote;"><a href="../../../../index.html#toc">Go to TOC</a></span>' >> "$file"
    fi
  else
    echo '<span style="float: footnote;"><a href="./index.html#toc">Go to TOC</a></span>' >> "$file"
  fi
}

它只是添加在取决于arg的../前面。我怎样才能让它变得更好?index.html#toc$2

答案1

我想到了这个。它有效,但如果您有更好的解决方案,请告诉我。

repeat(){
  END=$2
  for i in $(eval echo "{1..$END}")
  do
    echo -n "$1"
  done
}

append_footnote(){
  file=$1
  if [ "$#" -ge 2 ];then 
    depth=$2
    path_str=$(repeat '../' $depth)
    if [ $depth -gt 1 ];then
        echo "<span style='float: footnote;'><a href=\"${path_str}index.html#toc\">Go to TOC</a></span>" >> "$file"
    fi
  else
    echo '<span style="float: footnote;"><a href="./index.html#toc">Go to TOC</a></span>' >> "$file"
  fi
}

相关内容