将shell脚本转换为.bashrc中的函数[shell退出]

Mar*_*ert 0 bash shell

我有一个shell脚本,我想将其转换为可以包含在其中的函数.bashrc.除此之外#!/bin/bash,shell脚本包含以下函数的内容:

pdfMerge () {
    ## usage
    if [ $# -lt 1 ]; then
    echo "Usage: `basename $0` infile_1.pdf infile_2.pdf ... outfile.pdf"
    exit 0
    fi
    ## main
    ARGS=("$@") # determine all arguments
    outfile=${ARGS[-1]} # get the last argument
    unset ARGS[${#ARGS[@]}-1] # drop it from the array
    exec gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOUTPUTFILE=$outfile "${ARGS[@]}" # call gs
}
Run Code Online (Sandbox Code Playgroud)

它已经运行并将给定的pdf文件与ghostscript结合起来.但是,shell在调用函数后总是退出(如果没有给出参数,也是如此).怎么解决这个问题?

Nic*_*tot 6

该脚本旨在作为独立的可执行文件运行,因此在完成后退出.如果要将其用作函数,则需要删除强制执行此行为的两个元素:( exit 0替换为return)并exec在调用前执行gs -dBATCH ...:

pdfMerge () {
    ## usage
    if [ $# -lt 1 ]; then
        echo "Usage: $FUNCNAME infile_1.pdf infile_2.pdf ... outfile.pdf"
        return
    fi
    ## main
    ARGS=("$@") # determine all arguments
    outfile=${ARGS[-1]} # get the last argument
    unset ARGS[${#ARGS[@]}-1] # drop it from the array
    gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOUTPUTFILE=$outfile "${ARGS[@]}" # call gs
}
Run Code Online (Sandbox Code Playgroud)