Passing parameters to a Bash function

前端 未结 7 1182
北荒
北荒 2020-11-22 10:15

I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line.

I would like to pass param

相关标签:
7条回答
  • 2020-11-22 10:58

    Thought I'd pipe in with mention of another way to pass named parameters to bash... passing by reference. This is supported as of bash 4.0

    #!/bin/bash
    function myBackupFunction(){ # directory options destination filename
    local directory="$1" options="$2" destination="$3" filename="$4";
      echo "tar cz ${!options} ${!directory} | ssh root@backupserver \"cat > /mnt/${!destination}/${!filename}.tgz\"";
    }
    
    declare -A backup=([directory]=".." [options]="..." [destination]="backups" [filename]="backup" );
    
    myBackupFunction backup[directory] backup[options] backup[destination] backup[filename];
    

    An alternative syntax for bash 4.3 is using a nameref

    Although the nameref is a lot more convenient in that it seamlessly dereferences, some older supported distros still ship an older version so I won't recommend it quite yet.

    0 讨论(0)
提交回复
热议问题