接收文件名作为参数或使用标准输入的bash函数
我想围绕bash中的接收文件名作为参数或使用标准输入的bash函数,bash,function,input,Bash,Function,Input,我想围绕bash中的sha1sum函数编写一些包装。从手册页: SHA1SUM(1) User Commands SHA1SUM(1) NAME sha1sum - compute and check SHA1 message digest SYNOPSIS sha1sum [OPTION]... [F
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\u包装路径到\u文件
及
echo-n“blabla”|我的包装
我认为这与如何“完美”有关,但不确定如何做到这一点
编辑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
或:
这段代码适合我,把它放在一个名为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
}
谢谢这本身是可行的,但在我的脚本中,我的程序是防御性的(参见主要问题中的编辑)。现在,在脚本中使用时,出现了一个
未绑定变量错误。您知道如何修复,使其在编辑环境中工作吗?谢谢。这本身是可行的,但在我的脚本中,我的程序是防御性的(参见主要问题中的编辑)。现在,在脚本中使用时,出现了一个未绑定变量错误。知道如何修复以使其在编辑上下文中工作吗?请检查更新的答案,以便与noclobber nounset pipefail errexit一起使用
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
}