Bash从函数中提取元素

时间:2016-08-03 04:16:08

标签: bash function

我很想知道你是否可以从bash中的函数中提取行。说我有这个功能:

error_fn()
{
    echo "You need at least 2 command line arguments!"
    echo "Program existing because you said you had a typo, please try agian"
    echo "Sorry, one or both of the files that you entered was a directory, please try agian"
    echo "Sorry, one or both files were not located, please try again"
}

有没有办法从这个数组中提取第一个echo语句(echo“你需要至少2个命令行参数!”)?

我尝试过使用:

error_fn $1
error_fn ("$1")

但这似乎只输出函数中的所有echo语句。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您可以执行与以下内容类似的error_fn()并将索引值idx(从零开始,例如0 - 3)作为error_fn()的参数传递给error_fn() { array=( "You need at least 2 command line arguments!" "Program existing because you said you had a typo, please try agian" "Sorry, one or both of the files that you entered was a directory, please try agian" "Sorry, one or both files were not located, please try again" ) idx=$(($1)) if [ '0' -le "$idx" -a "$idx" -le '3' ] then printf "error: %s\n" "${array[idx]}" else printf "error: function index '%d' out of range.\n" "$idx" fi } 相应的错误输出。

$1

仔细看看,如果您有疑问,请告诉我。

对于一般的错误/使用函数,我通常更喜欢在 heredoc 中使用尽可能多的样板,同时能够通过{{1}传递错误消息对于功能。例如:

usage() {

    local ecode=${2:-0}     ## set exit code '0' by default

    test -n "$1" && printf "\n %s\n" "$1" >&2  ## print error msg (if any)

## heredoc of usage information
cat >&2 << USG

usage: ${0//*\//} _required_input_, etc..

This script ... (give description)

Options:

    -h  |  --help  program help (this file)

USG

    exit $ecode;
}

默认显示用法信息,如果错误字符串作为agrument 1给出,则显示错误除了用法之外,最后默认设置程序0的退出代码但是如果作为第二个参数传递,它将设置任何数字参数作为退出代码。实例

[ -z "$1" ] && usage "warning: insufficient input."  # General usage use.

[ -d "neededdir" ] || mkdir -p neededdir     # error on exit and set ecode 2
[ -d "neededdir" } || usage "error: unable to create 'neededdir'." 2

答案 1 :(得分:0)

该功能只是另一个创建输出的命令。你可以解析它。

error_fn | head -n 1

但是,如果您重写函数以获取参数并显示与该参数相关的错误消息,它可能会执行您打算执行的操作:

function error_fn {
  err="$1"

  case "$err" in
    EREFP) echo "Error: refining particles failed" >&2 ;;
    ECYCE) echo "Error: number of cycles exceeded" >&2 ;;
    EHUPM) echo "Error: hangup misdirected, dangling receiver" >&2 ;;
    *)     echo "Error: something's wrong (code:$err)" >&2 ;;
  esac
}

if ! refine_particles; then
  error_fn EREFP
else if ! hang_up_projections; then
  error_fn EHUPM
fi