1

I want to create a script on Linux to create some directories if they do not exists. The directories are declared inside the script itself (not being passed from command line):

#!/bin/bash

varBaseDir="/home/user"

# Directories to create
varAppDir="${varBaseDir}/app"
varAppDataDir="${varBaseDir}/appData"

if [[ -d ${varAppDir} ]]
        then
                echo "app dir exist"
        else
                echo "app dir does not exist! creating '${dir}' ..."
                mkdir -p ${dir}
                if test "$?" -eq "0"
                        then
                                        echo "succeeded."
                        else
                                echo "failed to create directory"
                fi
fi

As you can see I create one of the directories. Then I would need to repeat the same code again but with a different directory (next time I want the varAppDataDir to be created).

I tried to figure out how to declare a function:

my_function($dir) {
        echo $dir
}

my_funciotn("HELLO")

but I get error:

./test.sh: line 27: syntax error near unexpected token `$dir'
./test.sh: line 27: `my_function($dir) {'

So how to do this right?

2
  • 1
    Note that your entire script (except the part that tells you the dir didn't exist) can be condensed to mkdir -p "$dir" && echo "succeeded" || echo "failed". You don't need to test whether the dir exists, mkdir -p (at least with GNU mkdir) silently returns success if the dir exists, and creates it if it doesn't. Unless you really need to log that the dir didn't exist when the script was launched, you really don't need all that.
    – terdon
    May 25, 2022 at 14:53
  • @terdon Thanks for the tip. nice to know :)
    – DEKKER
    May 25, 2022 at 14:59

1 Answer 1

1

Functions don't have named arguments in POSIX shell or Bash. Instead, the arguments show up in the positional parameters, $1, $2, etc.

You'll have to manually copy them to named local variables if you want that. So:

foo() {
    local this="$1"
    local that="$2"
    printf "foo: that is '%s'\n" "$that"
}
foo one two

(local variables aren't specified in the standard, but pretty much all shells except ksh (ksh93?) treat them the same.)

See:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.