BASH: how to pass a default argument if no arguments after the first were passed

argumentsbashshell-script

I have a bash script with a case statement in it:

case "$1" in 
    bash)
        docker exec -it $(docker-compose ps -q web) /bin/bash
        ;;
    shell)
        docker exec -it $(docker-compose ps -q web) python manage.py shell
        ;;
    test)
        docker exec -it $(docker-compose ps -q web) python manage.py test "${@:2}"
        ;;
esac

On the test command, I want to pass the default argument of apps, but only if the user didn't pass any arguments other than test to the bash script.

So, if the user runs the script like this:

./do test

it should run the command

docker exec -it $(docker-compose ps -q web) python manage.py test apps

However, if they run the script like this:

./do test billing accounts

it should run the command

docker exec -it $(docker-compose ps -q web) python manage.py test billing accounts

How can I test for the existence of arguments after the first argument?

Best Answer

I'd try to use bash variable substitution:

   test)
        shift
        docker exec -it $(docker-compose ps -q web) python manage.py test "${@-apps}"
        ;;

Other way is to check $* instead of $1:

case $* in 
    bash)
         ...
    test)
         docker exec -it $(docker-compose ps -q web) python manage.py test apps
         ;;
    test\ *)
         docker exec -it $(docker-compose ps -q web) python manage.py test "${@:2}"
         ;;
Related Question