0

I want to pass directory name as the function's parameter and then check whether it exists or not. Here's what I got:

#!/bin/bash

my_function()   {
        dir="$1"
        if [ -d dir ]; then
                cd dir
        else
                mkdir dir
        fi
}
stafino
  • 37
  • 10
  • Now you can call your function in your script like so: `my_function "$1"` and call your script with `my_script SOMEDIR` (after doing `chmod 700 my_script`). –  Mar 01 '21 at 18:31
  • Of course there's a bit of circumlocution going on there, but you are doing fine this way. –  Mar 01 '21 at 18:35
  • You need to use `$` before `die` and double quote them. – choroba Mar 01 '21 at 18:36
  • Ah yes, I overlooked those, thanks @choroba. –  Mar 01 '21 at 18:37
  • What @choroba means is these occurences of dir: `-d "$dir"`, `cd "$dir"` and `mkdir "$dir"`. –  Mar 01 '21 at 18:44
  • 1
    so if you want to create the directory and `cd` to the directory you have to call your function twice? or do you want to `cd` to the directory after `mkdir`? and if that's the case then perhaps simplify by replacing the `if/then/fi` with `mkdir -p "${dir}"; cd "${dir}"` or `mkdir -p "$1"; cd "$1"` ... making sure to use double quotes around the variable references in case the directory name includes white space – markp-fuso Mar 01 '21 at 18:44
  • @markp-fuso will try that – stafino Mar 01 '21 at 18:45

1 Answers1

1

The way to expand variables (parameters) in the shell is to stick a $ in front of the variable name. dir is a constant string, $dir (or ${dir}) expands to the contents of the variable. To deal with whitespace in the value, you should use the expansion only inside double-quotes, so,

if [ -d "$dir" ]; then
    mkdir -- "$dir"

etc.

See http://mywiki.wooledge.org/BashGuide/Parameters and http://mywiki.wooledge.org/WordSplitting.

ilkkachu
  • 6,221
  • 16
  • 30