Search code examples
bashshellheredoc

How to use the install command with a heredoc


I'm trying to convert an install script to use the install command rather than creating a file and running chmod +x against it. This is the script right now:

#!/usr/bin/env bash

install_target=/usr/local/bin/my_prog
volatile_path=/this/path/could/change

cat << EOF > "$install_target"
#!/usr/bin/env bash

"$volatile_path/some_other_executable" "\$@"
EOF
chmod +x "$install_target"

What I'd prefer to do is something like:

#!/usr/bin/env bash

install_target=/usr/local/bin/my_prog
volatile_path=/this/path/could/change

install "$install_target" << EOF 
#!/usr/bin/env bash

"$volatile_path/some_other_executable" "\$@"
EOF

What am I missing to make this work?


Solution

  • Based on the comments, and assuming you're using a BSD version of install (GNU install has full help shown by install --help whereas BSD only shows basic usage) I think this is what you want to be doing:

    #!/usr/bin/env bash
    
    install_target=/usr/local/bin/my_prog
    volatile_path=/this/path/could/change
    temp_file=/tmp/$0.$$.$RANDOM
    
    cat << EOF > "$temp_file"
    #!/usr/bin/env bash
    
    "$volatile_path/some_other_executable" "\$@"
    EOF
    
    install -bd "$temp_file" "$install_target"
    rm -f "$temp_file"
    

    Untested, but using process substitution should remove the need for a temp file:

    #!/usr/bin/env bash
    
    install_target=/usr/local/bin/my_prog
    volatile_path=/this/path/could/change
    
    install -bd <(cat << EOF
    #!/usr/bin/env bash
    
    "$volatile_path/some_other_executable" "\$@"
    EOF
    ) "$install_target"