I'm new to shell script, so any information is not trivial at all.
I'm writing a generic function create_dir
that take a variable $dirname
and an option variable $function
to generate a directory. If the optional $function
is absent, the default function is mkdir
. Like this:
File ~/bin/lib/create_dir.sh
:
#!/bin/bash
create_dir()
{
DIRNAME=$1
FUNCTION=${2:-mkdir}
$FUNCTION $DIRNAME
}
export -f create_dir
That works fine.
Now I import this into another file ~/bin/create_app
#!/bin/bash
. "${HOME}/bin/lib/create_dir.sh"
DIRNAME=$1
FUNCTION="python manage.py startapp"
create_dir $FUNCTION $DIRNAME
When I run create_app
it imported the create_dir
but the variable $FUNCTION
it feeds the create_dir
is wrong. The variable $FUNCTION
has only one word python
instead of python manage.py startapp
as I wanted.
Why? How to fix it?
You should quote the argument like this:
"$FUNCTION"
. Otherwise, the shell will runfollowed by all the words in the first argument to
create_app
. This way the first argument tocreate_dir
will bepython
and the second onemanage.py
.You are always on the safe side if you put double quotes around your variable expansions. This will prevent the shell from splitting the value of that variable into separate words, which the function then regards as different arguments when you pass to it that variable as an argument.
There are cases where you can go without quotes, for example in the line
or more generally
as the bash will automatically assume that you want to assign the entire value of
var
to the variablevar2
. On the other hand, if you write the value directly, you need to use quotes: