bash函数,该函数接收文件名作为参数或使用标准输入

时间:2020-03-04 11:09:44

标签: bash function input

我想在bash中为sha1sum函数编写一些包装。从手册页:

SHA1SUM(1)                                          User Commands                                          SHA1SUM(1)

NAME
       sha1sum - compute and check SHA1 message digest

SYNOPSIS
       sha1sum [OPTION]... [FILE]...

DESCRIPTION
       Print or check SHA1 (160-bit) checksums.

       With no FILE, or when FILE is -, read standard input.

如何设置包装程序,使其以相同的方式工作?即:

my_wrapper(){
  # some code here
}

可以同时用作:

my_wrapper PATH_TO_FILE

echo -n "blabla" | my_wrapper

我认为这与Redirect standard input dynamically in a bash script有某种联系,但不确定如何使其“很好”。

编辑1

我以一种非常防御性的方式进行编程,因此我在整个脚本中都使用了它:

# exit if a command fails
set -o errexit
# make sure to show the error code of the first failing command
set -o pipefail
# do not overwrite files too easily
set -o noclobber
# exit if try to use undefined variable
set -o nounset

有什么用吗?

3 个答案:

答案 0 :(得分:1)

您可以使用以下简单包装器:

args=("$@")         # save arguments into an array
set -o noclobber nounset pipefail errexit
set -- "${args[@]}" # set positional arguments from array

my_wrapper() {
   [[ -f $1 ]] && SHA1SUM "$1" || SHA1SUM
}

my_wrapper "$@"

请注意,您可以使用:

my_wrapper PATH_TO_FILE

或:

echo -n "blabla" | my_wrapper

答案 1 :(得分:1)

此代码对我有用,将其放在名为wrapper的文件中

#!/bin/bash


my_wrapper(){
    if [[ -z "$1" ]];then
        read PARAM
    else
        PARAM="$1"
    fi

    echo "PARAM:$PARAM"
}

在您的环境中加载功能

. ./wrapper

使用输入管道测试功能

root@51ce582167d0:~# echo hello | my_wrapper
PARAM:hello

使用参数测试功能

root@51ce582167d0:~# my_wrapper bybye
PARAM:bybye

答案 2 :(得分:0)

好吧,所以这里发布的答案通常很好,但以我为例,使用防御性编程选项:

# exit if a command fails
set -o errexit
# exit if try to use undefined variable
set -o nounset

事物无法正常运行。所以我现在正在使用这种东西:

digest_function(){
    # argument is either filename or read from std input
    # similar to the sha*sum functions

    if [[ "$#" = "1" ]]
    then
        # this needs to be a file that exists
        if [ ! -f $1 ]
        then
            echo "File not found! Aborting..."
            exit 1
        else
            local ARGTYPE="Filename"
            local PARAM="$1"
        fi
    else
        local ARGTYPE="StdInput"
        local PARAM=$(cat)
    fi

    if [[ "${ARGTYPE}" = "Filename" ]]
    then
        local DIGEST=$(sha1sum ${PARAM})

    else
        local DIGEST=$(echo -n ${PARAM} | sha1sum)
    fi
}