linux - Bash - 如何在这种情况下调用函数

标签 linux bash shell unix

你好,我想知道将这段代码分解成函数的最佳方法是什么

 case $# in
    1) ports='1-1023'
       host=$1 ;;
    2) ports=$1
       host=$2 ;;
    *) echo 'Usage: portscan [port|range] host'
       exit 1 ;;
esac
# check port range
if [ "$(echo $ports | grep '^[1-9][0-9]*-[1-9][0-9]*$')" != "" ]; then
    firstport=$(echo $ports | cut -d- -f1)
    lastport=$(echo $ports | cut -d- -f2)
elif [ "$(echo $ports | grep '^[1-9][0-9]*$')" != "" ]; then
    firstport=$ports
    lastport=$ports
else
    echo "$ports is an invalid port(s) value"
    exit 2
fi
# check firstport > lastport
if [ $firstport -gt $lastport ]; then
    echo $firstport is larger than $lastport
    exit 3
fi

** 像这样在 main 中调用它们****

# Check parameters and exit 1 if problem
check_parms $#
# Check port range and exit 2 if problem
check_ports $ports
# Check port order and exit 3 if problem
check_order $firstport $lastport

最佳答案

当您调用 bash 函数时,它也有自己的 $*、$#、$1、.... 来反射(reflect)该调用。所以你可以构建一堆小函数,比如

function check_parms() {
    local num=$# <----------- I changed this line
    case $num)
    ... etc
}

然后,

function check_ports() {
    local ports=$1
    if ...
}

等等

我希望这能给你一些重构的想法。如果您正在考虑 sourceing bash 脚本,一个好主意可能是 unset 您在脚本末尾定义的函数。

here 上的一个不错的教程

在主 block 中,像调用任何其他 bash 函数一样调用它。例如:

echo "hello"
check_parms $*
check_ports $ports
echo "..."

关于linux - Bash - 如何在这种情况下调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27052633/

相关文章:

c++ - const char& 作为函数的参数

python - 你如何将 bash 别名移植到 ipython > 0.10?

linux - 不断将控制台的输出写入文件

java - 如何与现有的java进程通信

linux - Bash while 循环使用包含本地 $variable 的远程 grep

Linux 项目 : bash script to archive and remove files

python - 即使在 linux 中从 python 脚本执行脚本后,也永久设置环境变量

bash - Shell-script-internal encoding 与重定向输出不同

linux - 在 Debian 上链接依赖于位置的程序集

python - 脚本语言 : Max. 行长