Variables as commands in bash scripts

前端 未结 5 1431
名媛妹妹
名媛妹妹 2020-11-28 10:54

I am writing a very simple bash script that tars a given directory, encrypts the output of that, and then splits the resultant file into multiple smaller files since the bac

5条回答
  •  一向
    一向 (楼主)
    2020-11-28 11:43

    eval is not an acceptable practice if your directory names can be generated by untrusted sources. See BashFAQ #48 for more on why eval should not be used, and BashFAQ #50 for more on the root cause of this problem and its proper solutions, some of which are touched on below:

    If you need to build up your commands over time, use arrays:

    tar_cmd=( tar cv "$directory" )
    split_cmd=( split -b 1024m - "$backup_file" )
    encrypt_cmd=( openssl des3 -salt )
    "${tar_cmd[@]}" | "${encrypt_cmd[@]}" | "${split_cmd[@]}"
    

    Alternately, if this is just about defining your commands in one central place, use functions:

    tar_cmd() { tar cv "$directory"; }
    split_cmd() { split -b 1024m - "$backup_file"; }
    encrypt_cmd() { openssl des3 -salt; }
    tar_cmd | split_cmd | encrypt_cmd
    

提交回复
热议问题