[英]bash function that either receives file name as argument or uses standard 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.
我如何设置我的包装器以使其以相同的方式工作? IE:
my_wrapper(){
# some code here
}
这可以作为:
my_wrapper PATH_TO_FILE
和
echo -n "blabla" | my_wrapper
我认为这与在 bash 脚本中动态重定向标准输入有某种关系,但不确定如何使它“很好”。
编辑 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
有什么可以与之配合的吗?
您可以使用这个简单的包装器:
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
这段代码对我有用,把它放在一个名为 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
好的,所以这里发布的答案通常很好,但在我的情况下有防御性编程选项:
# 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.