Issue
Say I have a variable command $EXPORT
that is defined as something like
EXPORT=$(eval "export PYTHONPATH=/path/to/package1:$PYTHONPATH")
However, I want the command to export a new package2 instead of package1 to $PYTHONPATH
. Note that I want to do it by modifying the current $EXPORT
variable instead of redefining it. What I have tried is to replace the string "/path/to/package1"
by "/path/to/package2"
:
echo ${$EXPORT//"/path/to/package1"/"/path/to/package2"}
but I am getting "bad substitution" error.
So what is the proper way to modify a variable command in bash?
Solution
Don't store code in variables, Variables are for storing data, functions are for storing code. See https://mywiki.wooledge.org/BashFAQ/050.
I think you might want this (untested):
do_export() { export PYTHONPATH="${1:-/path/to/package1}:$PYTHONPATH"; }
mycmd() { ls "${1:-./}"; )
which you'd then run as do_export '/path/to/package2'
to prepend package2
instead of package1
to PYTHONPATH
and mycmd ..
to run ls
on the parent dir for example.
Answered By - Ed Morton Answer Checked By - Pedro (WPSolving Volunteer)