0

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?

3
  • 1
    You should quote the argument like this: "$FUNCTION". Otherwise, the shell will run create_dir python manage.py startapp ... followed by all the words in the first argument to create_app. This way the first argument will be python and the second one manage.py Feb 1, 2019 at 19:33
  • Stefan is right. Important rule in shell programming: When in doubt: quote. To check your scripts you can use shellcheck
    – Ralf
    Feb 1, 2019 at 19:39
  • oh my god I saw somewhere they emphasized the importance of putting variables between double quotes. Now I seee Feb 1, 2019 at 19:39

1 Answer 1

0

You should quote the argument like this: "$FUNCTION". Otherwise, the shell will run

create_dir python manage.py startapp ... 

followed by all the words in the first argument to create_app. This way the first argument to create_dir will be python and the second one manage.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

DIRNAME=$1

or more generally

var2=$var

as the bash will automatically assume that you want to assign the entire value of var to the variable var2. On the other hand, if you write the value directly, you need to use quotes:

string="Hello World"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .