The following code is meant to look for subdirectories in ~/Downloads
. I run it with . ./script.sh
. It will find them even when the user submits an incomplete name.
#!/usr/bin/bash echo -e "\nGive me the name of a nonexitent directory and I will look for it in ~/Downloads?\n" read word TOGOs=("$(find ~/Downloads -maxdepth 1 -iname "*$word*" -type d -execdir echo {} + | sed 's;./;/home/smith/Downloads/;g')" "") for togo in ${TOGOs[@]} do if [[ $togo != "" ]]; then echo $togo export togo && cd $togo && return 0 else echo "Haven't found it in ~/Downloads ." && cd ~/Downloads #This line does not work fi done
The if
part works as expected - when I give it a name/part of the name of a subdirectory of ~/Downloads/
, but the else
part of the block never gets executed when I give it a nonexisting directory. I can get the else
part executed when I get rid of the loop, like so:
#!/usr/bin/bash echo -e "\nGive me the name of a nonexitent directory and I will look for it in ~/Downloads?\n" read word TOGO=$(find ~/Downloads -maxdepth 1 -iname "*$word*" -type d -execdir echo {} + | sed 's;./;/home/smith/Downloads/;g') if [[ $TOGO != "" ]]; then echo $TOGO export TOGO cd $TOGO && return 0 else echo "Haven't found it in ~/Downloads." && cd ~/Downloads fi
Why is it so the else
arm gets executed when I get rid of the loop? How might I get my code executed while preserving the loop?