Home > database >  How can I define a fallback command to be called if a command is not available
How can I define a fallback command to be called if a command is not available

Time:08-13

I want to call task (https://taskfile.dev/) in a single line command. But on some systems task is installed as task, while on others as go-task. On my system I have defined an alias in the shell task=go-task.

Is there some concisely syntax:

task --help

maybe similar to default variable values, ${task:-go-task} --help ?

This would be helpful in cases like, podman and docker or many more as well.

edit:

if command -v task &> /dev/null ; then task=task ; else task=go-task ; fi && $task --help

does not work, since task is an alias. In this case I get bash: task: command not found....

CodePudding user response:

Try with:


# Check command

command -v main-command > /dev/null && CMD=main-command || CMD=fallback-command

# Execute command

${CMD}

CodePudding user response:

Try this function (instead of alias) :

task(){
    declare -a cmds=($FUNCNAME go-task) cmd c
    for c in "${cmds[@]}"; do
        type -f "$c" &> /dev/null && { cmd="$c"; break; }
    done
    test -v cmd && command $cmd "$@" ||
        { echo "bash: commands [${cmds[*]}] not found."; return 127; }
}
  • Related