Skip to content

File Operations

ensure_file.sh

File-related ensure functions, allowing to manage files and their contents.

Functions

ensure_file_content_includes

Ensure that a file includes a line or block of lines, inserting or replacing it if needed.

Examples

  • Disable password authentication in SSH
    ensure_file_content_includes --match='\s*#?\s*PasswordAuthentication\s.*' \
      /etc/ssh/sshd_config <<< "PasswordAuthentication no"
    [ $ENSURE_CHANGED -eq 0 ] || ensure_service_active --reload ssh
    
Arguments
  • --match={expr}:

    A regular expression ("sed -E" syntax) used to identify the target line or block that will be replaced. Always matches whole lines, do not use ^ and $!

  • {file...}:

    Filenames in which the content should be checked & updated.

Standard input
  • The content block that should be included in the file. May only be a text block, not a binary stream.


ensure_file_content_equals

Ensure that a file exactly matches the specified content, replacing it if needed.

Examples

  • Replace file content of /etc/issue
    ensure_file_content_equals /etc/issue <<EOF
    Welcome to my System.
    Feel free to hack around!
    EOF
    
  • Install a shell script to /usr/local/bin
    ensure_file_present --mode=755 /usr/local/bin/my-shell-script.sh
    ensure_file_content_equals /usr/local/bin/my-shell-script.sh < ./assets/my-shell-script.sh
    
Arguments
  • {file...}:

    Filenames in which the content should be checked & updated.

Standard input
  • The desired content of the file. May be a binary stream.


ensure_file_absent

Ensure that files are absent, deleting them if they exist.

Examples

  • Delete a file
    ensure_file_absent /tmp/somefile.txt
    
Arguments
  • --recursive:

    If specified, the function will delete directories and their contents recursively.

  • {file...}:

    Filenames or directories to be deleted.


ensure_file_present

Ensure that files or directories are present and match the given metadata, creating or updating them if they do not exist.

Examples

  • Create an empty file with specific permissions
    ensure_file_present --mode=644 /tmp/somefile.txt
    
Arguments
  • --type=directory|symlink|file:

    Specify the type of file to ensure (default is 'file').

  • --force-recreate:

    Danger: If the file exists but the type is wrong, the default behaviour is to fail. With this option, the file will be deleted and recreated, which includes recursively deleting directories!

  • --link-target={target}:

    Only used if --type=symlink, specifies the target of the symlink.

  • --user={user}:

    The user that should own the file.

  • --group={group}:

    The group that should own the file.

  • --permissions={755}:

    The permissions that should be set for the file (in octal notation).

  • {file...}:

    Filenames or directories to be checked & updated.