Issue
Trying to run a python script via bash/shell script, figuring out what's the best way to accept multiple parameters in an argument and loop through all the parameters in $5 to run the same command on each of the address in $5. Also, is there a way not to pass in empty parameters while running the shell script? Below is what I worked on so far but confused on special parameters concept to use here https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html
#!/bin/bash
# Arguments
echo "Service: $1"
echo "Action: $2"
echo "file: $3"
echo "DockerV: $4"
echo "Address: $5"
python /scripts/service.py -s "$1" -t "$2" "$5"
Running it this way works, but only if empty quotes are passed in---
/users/shellScripts/serviceTest.sh "ALL" "Stop" " " " " "11.45.26.13"
Running it this way does not works, as $5 has more than 1 argument---
/users/shellScripts/serviceTest.sh "ALL" "Stop" " " " " "11.45.26.13 11.45.26.14 11.45.26.15"
I tried the script I wrote above but confused on the concept of special parameters of bash/shell. Expecting to execute the shell script without empty parameters(maybe setting them as optional) also having the ability to pass in multiple parameters into an argument and loop through all the parameters in $5 to run the same command on each of the address in $5.
Solution
Truly optional position arguments are very hard in general and likely impossible in your specific case, but you can use an options parser like getopts.
#!/bin/bash
args=()
while getopts ':s:t:' opt ; do
case $opt in
s) args+=( -s "$OPTARG" ) ;;
t) args+=( -t "$OPTARG" ) ;;
?) echo "Invalid option $OPTARG" ;;
:) echo "Option $OPTARG needs an argument" ;;
esac
done
shift $(( OPTIND - 1 ))
for ip in "$@" ; do
python /scripts/service.py "${args[@]}" "$ip"
done
Example invocation:
/users/shellScripts/serviceTest.sh -s "ALL" -t "Stop" 11.45.26.13 11.45.26.14 11.45.26.15
Important things to note:
getopts
will help you handle all the optional content.- The options get built into an array to help pass them to the python script - see BashFAQ/50 for an in-depth explanation of why.
- After
getopts
is done,shift
is invoked to throw the options out so you're left with only the positional arguments. You can then iterate them withfor ip in "$@"
. - Don't shove all of the positional arguments into quotes. It's easier to do something with each of them individually if you pass them to the script as separate arguments than if you pass them as one argument that the script then has to deconstruct.
Answered By - tjm3772 Answer Checked By - Cary Denson (WPSolving Admin)