Sample Header Ad - 728x90

script arguments in bash

2 votes
1 answer
251 views
I am working on a a script that need to take two script arguments and use them as variables in the script. I couldn't get this working and unable to find out what I am doing wrong. I see the issue is the second argument, as I see in some of my tests(as mentioned in the bottom of this post) it is not being read. Here is the code: #!usr/bin/bash help() { echo "" echo "Usage: $0 -p patch_level -e environment" echo -e "\t-p Patch level that you are tryin to update the server" echo -e "\t-e Environment that the patch need to be run on" exit 1 # Exit script after printing help } while getopts "p:e" opt do case "${opt}" in p ) patch_level="$OPTARG" ;; e ) _env="$OPTARG" ;; ? ) help ;; # Print help in case parameter is non-existent esac done if [ -z "$patch_level" ] || [ -z "$_env" ]; # checking for null parameter then echo "Some or all of the parameters are empty"; help else echo "$patch_level and $_env" fi When I run the script like below , I get this. > ./restart.sh -p 2021 -e sbx > Some or all of the parameters are empty > Usage: ./restart.sh -p patch_level -e environment > -p Patch level that you are tryin to update the server > -e Environment that the patch need to be run on Note: I modeled my code based on the third answer in this https://unix.stackexchange.com/questions/31414/how-can-i-pass-a-command-line-argument-into-a-shell-script I see the issue is with the second variable (-e). Because if I change the last if statement from "or to and", the script runs but doesn't print anything for the second variable: here is what I am talking about if [ -z "$patch_level" ] && [ -z "$_env" ]; the output is ./restart.sh -p 2021 -e sbx 2021 and This server will be patched to 2021 I am on Ubuntu if that matters.
Asked by MO12 (409 rep)
Jan 28, 2024, 08:43 PM
Last activity: Jan 29, 2024, 03:59 PM