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!

2
  • Please add a suitable shebang (#!/bin/bash) and then paste your script at shellcheck.net and try to implement the recommendations made there. Commented Oct 4, 2021 at 19:00
  • 2
    $1 is the first argument to the function. You called the function with no arguments, so $1 is not defined. Commented Oct 4, 2021 at 19:00

1 Answer 1

1

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

check_for_file "$1"
Sign up to request clarification or add additional context in comments.

1 Comment

In 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".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.