Обработка необязательных аргументов с помощью getopts в bash

Применен ответ из вики Debian, когда что-то пошло не так с драйвером nvidia:

hit Ctrl+alt+F2

login as root

apt-get purge nvidia. 

(don't forget the "." dot) It erases every package with "nvidia" on its name

/etc/init.d/gdm3 stop # (gdm3 for gnome 3)
apt-get install --reinstall xserver-xorg
apt-get install --reinstall xserver-xorg-video-nouveau
killall Xorg
reboot

Xorg should reconfigure itself, if not run a terminal and pass

X -configure

debian wiki:Откат в случае сбоя

0
29.10.2020, 16:52
2 ответа
#!/bin/sh -

# Beware variables can be inherited from the environment. So
# it's important to start with a clean slate if you're going to
# dereference variables while not being guaranteed that they'll
# be assigned to:
unset -v file arg1 arg2

# no need to initialise OPTIND here as it's the first and only
# use of getopts in this script and sh should already guarantee it's
# initialised.
while getopts a:b:i: option
do
  case "${option}" in
    (a) arg1=${OPTARG};;
    (b) arg2=${OPTARG};;
    (i) file=${OPTARG};;
    (*) exit 1;;
  esac
done

shift "$((OPTIND - 1))"
# now "$@" contains the rest of the arguments

if [ -z "${file+set}" ]; then
  if [ "$#" -eq 0 ]; then
    echo >&2 "No input file specified"
    exit 1
  else
    file=$1 # first non-option argument
    shift
  fi
fi

if [ "$#" -gt 0 ]; then
  echo There are more arguments:
  printf ' - "%s"\n' "$@"
fi

Я изменил bashна sh, так как в этом коде нетbash-ничего конкретного.

1
18.03.2021, 22:53

Я хотел бы расширить отличный ответ Стефана Шазела , чтобы использоватьбашизмбольше в стиле вопроса, а именно[ -z "$file" ] && { echo "No input file specified" ; exit; }--вместо использования ifs .

#!/bin/bash
unset -v file arg1 arg2

while getopts "a:b:i:" option; do
    case "$option" in
        a ) arg1="$OPTARG";;
        b ) arg2="$OPTARG";;
        i ) file="$OPTARG";;
        * ) exit 1;;
    esac
done

shift "$((OPTIND - 1))"

[ -z "$file" ] && [ "$#" -eq 0 ] && { echo "No input file" >&2; exit 1; }
[ -z "$file" ] && [ "$#" -gt 0 ] && { file="$1"; shift; }

echo "DEBUG: arg 1 is $arg1"
echo "DEBUG: arg 2 is $arg2"
echo "DEBUG: file  is $file"

[ "$#" -gt 0 ] && { echo "More arguments"; printf " - %s\n" "$@"; }
0
18.03.2021, 22:53

Теги

Похожие вопросы