Evgenii Legotckoi
Dec. 2, 2018, 8:58 p.m.

Using getopts in bash scripts to pass parameters

Content
  1. 1.

When developing a site to automate the deployment process, I wrote several bash scripts.

To customize the behavior of scripts, I use the transfer of arguments, which are handled in the bash script by the getopts library.


Getopts

Scripts typically use getopts to analyze the arguments passed to them. When you specify args on the command line, getopts analyzes these arguments instead of a script, and then the script uses the parsed data that getopts parsed.

For example, in my case I use several actions that must be performed by the script.

  1. while getopts p:dicmz option
  2. do
  3. case "${option}"
  4. in
  5. p) PASSWORD=${OPTARG};; # Password for reload services: gunicorn and celery
  6. d) DEPLOY_PROJECT_PACKAGES=true;; # Deploy local projects packages
  7. i) INSTALL_REQUIREMENTS=true;; # Install or update new packages from requirements
  8. c) COLLECTSTATIC=true;; # Execute collectstatic
  9. m) MIGRATE=true;; # Execute migrate
  10. z) INGORE_BACKUP=true;; # WARNING: Be careful with this option.
  11. # Do not use it, when execute migrations or add new application or git submodule
  12. esac
  13. done

I am running a project on the site, installing or updating required packages in a project, building a new statics, migrating a database and, if necessary, ignoring the creation of a project backup, although I rarely use this. It is better to be safe once again and perform a backup.

Thus, the script can be run with parameters in this way.

  1. ./deploy.sh -icm -p mypassword

In this case, a password will be transferred to perform specific functions requiring a password, and installation or updating of required packages, static build and database migration will be performed.

The passed parameter not requiring an argument will be checked in the conditions so

  1. if [ "$INGORE_BACKUP" ]
  2. then
  3. # Deployment without backup"
  4. else
  5. # Execute backup
  6. fi

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html