Bash wrapper that abbreviates strings

Sati :

I have a python program that customizes the page number of a pdf file.

Its usage is like so:

usage: pagelabels [-h] [--outfile out.pdf] [--delete | --update]
                  [--startpage STARTPAGE]
                  [--type {arabic,roman lowercase,roman uppercase,letters lowercase,letters uppercase}]
                  [--prefix PREFIX] [--firstpagenum FIRSTPAGENUM]
                  [--load other.pdf]
                  file.pdf

Add page labels to a PDF file

I have written a wrapper shell script to save up on typing when calling pagelabels above.

#!/bin/bash
# Wrapper for `addpagelabels.py`.

display_usage() {
    echo "Wrapper for addpagelabels.py"
    echo -e "\nUsage: <inputpdf> <startpage> <type> <firstpagenum>\n"
    echo -e "<type>:\n a=arabic;\n r=roman lowercase;\n R=roman uppercase;\n l=letters lowercase;\n L=letters uppercase.\n"
    echo "Output file would be filename_toc.pdf"
}

if [ $# -eq 0 ]; then
  display_usage
  exit 1

else

    a='arabic'
    r='roman lowercase'
    R='roman uppercase'
    l='letters lowercase'
    L='letters uppercase'

python3 -m pagelabels --startpage $2 --type $3 --firstpagenum $4 --outfile ${1%%.*}_toc.pdf $1
exit 0

fi

The string variables defined in the script cannot be invoked by the third argument a below.

$ bash pdfpgn.sh dtjl.pdf 2 a 297
usage: addpagelabels.py [-h] [--delete] [--startpage STARTPAGE]
                        [--type {arabic,roman lowercase,roman uppercase,letters lowercase,letters uppercase}]
                        [--prefix PREFIX] [--firstpagenum FIRSTPAGENUM]
                        [--outfile out.pdf]
                        file.pdf
addpagelabels.py: error: argument --type/-t: invalid choice: 'a' (choose from 'arabic', 'roman lowercase', 'roman uppercase', 'letters lowercase', 'letters uppercase')

What is the right way to do this?

Charles Duffy :

Consider an associative array (bash's equivalent to a Python dict, though its keys and values can only be strings).

Consider:

#!/bin/bash
case $BASH_VERSION in ''|[123].*) echo "ERROR: Bash 4.0+ required" >&2; exit 1;; esac

declare -A type_abbreviations=(
    [a]='arabic'
    [r]='roman lowercase'
    [R]='roman uppercase'
    [l]='letters lowercase'
    [L]='letters uppercase'
)

filename=$1
startpage=$2
type=$3
startpagenum=$4

[[ ${type_abbreviations[$type]} ]] && type=${type_abbreviations[$type]}

exec python3 -m pagelabels \
  --startpage "$startpage" \
  --type "$type" \
  --firstpagenum "$startpagenum" \
  --outfile "${filename%%.*}_toc.pdf" \
  "$filename"

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=390953&siteId=1