15

So I have a question about get opts in bash. I want to get the value of the arguments if they are present but if they are not present to use a default value. So the script should take a directory and an integer but if they aren't specified then $PWD and 3 should be default values. Here is what

while getopts "hd:l:" opt; do
    case $opt in
        d ) directory=$OPTARG;;
        l ) depth=$OPTARG;;
        h ) usage
        exit 0;;
        \? ) usage
        exit 1;;
    esac
Greg
  • 737
  • 4
  • 13
  • 21

2 Answers2

31

You can just provide default value before while loop:

directory=mydir
depth=123
while getopts "hd:l:" opt; do
    case $opt in
        d ) directory=$OPTARG;;
        l ) depth=$OPTARG;;
        h ) usage
        exit 0;;
        *) usage
        exit 1;;
    esac
done
echo "<$directory> <$depth>"
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • So I did that (makes total sense) but the directory and depth never change – Greg Feb 27 '14 at 04:38
  • So if the argument exists then I want to change the variable directory to whatever is passed into option -d but if it is not present then just leave it at the current working directory. – Greg Feb 27 '14 at 04:44
  • you can just do `-d ) cd "$OPTARG";;` for that – anubhava Feb 27 '14 at 04:51
  • is there a way to check if its valid? – Greg Feb 27 '14 at 05:00
  • yes sure you can do: `-d ) [[ -d "$OPTARG" ]] && cd "$OPTARG";;` – anubhava Feb 27 '14 at 05:05
  • ok thanks a lot for helping me out but it still doesn't change directories – Greg Feb 27 '14 at 05:07
  • 1
    it does change but shell scripts are run in a sub shell so changed directory is not reflected in parent shell – anubhava Feb 27 '14 at 05:07
  • 2
    also I need to humbly point that question was about setting default values which my answer provides. Would it not be better to ask a separate question about directory changing problem after accepting this answer. – anubhava Feb 27 '14 at 05:08
  • I figured it all out. Thanks for helping me out! – Greg Feb 27 '14 at 05:13
2

After your getopts, try this

if [ -z "$directory" ]; then directory="directory"; fi

-z means if the variable $directory is null or empty. Then if user doesnt enter an argument for -d, then the script will default to directory="/whatever/files/"

At least if I understand your question correctly, this should give you a default value for -d if a value is not entered.

Puffy
  • 41
  • 3
  • Please provide additional details in your answer. As it's currently written, it's hard to understand your solution. – Community Aug 30 '21 at 06:51