I have a shell script in which I am passing the same value many times as arguments. Instead of hardcoding this redundant value across all py scripts, I wanted to see if I can work with variables and pass those into the py script as arguments.
Here is the script.sh:
python A.py --month=10
python B.py --country=USA --month=10
I would like something like this:
#Setting variables to pass into args
country=USA
month=10
python A.py --month=month
python B.py --country=country --month=month
How would I do this?
To access the value of any variable in shell script, you can do it using the $
sign.
So below is how you can do it:
#Setting variables to pass into args
country=USA
month=10
python A.py --month="$month"
python B.py --country="$country" --month="$month"
If you have to use arguments passed to script, try something like below
script SomeMonth SomeCountry
Then in script
python A.py --month="$1"
python B.py --country="$2" --month="$1"
The positional parameters..
$0 = script (script Name)
$1 = SomeMonth (first argument)
$2 = SomeCountry (Second argument)
And so on..
Just to add something to the other correct answers. If you use those arguments many times, you can also embed the argument name together with its value, and save typing and errors:
# Setting variables to pass into args
p_country="--country=USA"
p_month="--month=10"
python A.py $p_month
python B.py $p_country $p_month
Note 1: beware of values containing spaces, or any other "strange" characters (meaningful to the shell). Ordinary words or numbers, like "USA" and "10" pose no problems.
Note 2: you can also store multiple "arg=value" in a single variable; it can save even more typing. For example:
p_m_and_c="--country=USA --month=10"
...
python B.py $p_m_and_c
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.