Search code examples
shellgetopts

Correct way of using getopts


Executing following script gives error for mkdir command

PATH=/root
while getopts "r" name;
do
    case $name in
        r)
            PATH=/home
            ;;
        *)
            echo "Usage: $0 -r"
            ;;
    esac
done

echo $PATH
mkdir new

error:

./test.sh: line 15: mkdir: command not found

What's wrong in this script ?


Solution

  • Your problem doesn't really have anything to do with getopts.

    The problem is the first line:

    PATH=/root
    

    or, if it's executed, this line:

    PATH=/home
    

    This sets the search path for commands to just the /root or /home directory. (Typically neither of those directories contains any commands).

    Setting $PATH throws away the previous value. mkdir is probably in /bin, but since /bin is no longer in $PATH, the shell can't find it.

    You don't get an error on the getopts command because it's built into the shell you're using.

    If you want to add /root to your $PATH, use:

    PATH="/root:$PATH"
    

    or

    PATH="$PATH:/root"
    

    But nothing in your script appears to depend on having /root in your $PATH. Why are you doing PATH=/root in the first place? If you're trying to set your current working directory to /root or /home, you want the chdir command.