bash脚本将参数回显到单独的行中

时间:2015-05-17 10:43:59

标签: bash unix scripting arguments lines

我必须编写此脚本来分隔在命令行中输入的参数。 到目前为止,这是脚本:

# template.sh
function usage
{
  echo "usage: $0 arguments ..."
  if [ $# -eq 1 ]
  then echo "ERROR: $1"
  fi
}

# Script starts after this line.

case $1 in
  *?)echo "My Name"
     date
     echo
     echo $*
     echo "*****"
     ;;
  *)usage
     ;;
esac

我需要获得的是当我使用它需要的脚本时:

$ ./template.sh peter frederick chang
My Name
Sun May 17 11:28:46 PDT 2015

peter
*****
frederick
*****
chang
*****

但相反,我得到了:

$ ./template.sh peter frederick chang
My Name
Sun May 17 11:28:46 PDT 2015

peter frederick chang
*****

1 个答案:

答案 0 :(得分:3)

使用printf代替echo这样的"$@"来打印不同行的参数:

# Script starts after this line.
case $1 in
  *?)echo "My Name"
     date
     echo
     printf "%s\n*****\n" "$@"
     ;;
  *)usage
     ;;
esac

这将打印:

My Name
Sun May 17 06:50:26 EDT 2015

peter
*****
frederick
*****
chang
*****