1

I am calling the bash script mkproj.sh by using the command ./mkproj.sh. I also try calling it with arguments: ./mkproj.sh hello but my script returns a null $1 when I put echo "$1" in the script. I am not sure why it won't recognize the command-line arguments.

check_for_file()
{
if [ $# -eq 0 ]; then
        local testing_file=myproject
else
        local testing_file=$1
fi

if [ -d $testing_file ]; then
        echo "Directory name already exists"
        exit
else
        mkdir -p "$testing_file"/{archive,backups,docs/{html,txt},assets,database,src/{sh,c}}
fi

}
check_for_file


Thank you!

gogo
  • 53
  • 1
  • 12
  • Please add a suitable shebang (`#!/bin/bash`) and then paste your script at http://www.shellcheck.net/ and try to implement the recommendations made there. – Cyrus Oct 04 '21 at 19:00
  • 2
    `$1` is the first argument to the function. You called the function with no arguments, so `$1` is not defined. – William Pursell Oct 04 '21 at 19:00

1 Answers1

1

Positional parameters within functions shadow global positional parameters that script received. You need to call your function like that:

check_for_file "$1"
Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer), note the section _Answer Well-Asked Questions_, and the bullet point therein regarding questions that "have been asked and answered many times before". – Charles Duffy Oct 04 '21 at 19:01