aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/%HOME%/.bash_utils/file.sh
blob: 6034713ddded6d1a26891ee4026c076b63d167a7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env bash

# Copyright (c) 2016 Egor Tensin <Egor.Tensin@gmail.com>
# This file is part of the "Cygwin configuration files" project.
# For details, see https://github.com/egor-tensin/cygwin-home.
# Distributed under the MIT License.

swap_files() (
    set -o errexit -o nounset -o pipefail

    if [ "$#" -ne 2 ]; then
        echo "usage: ${FUNCNAME[0]} PATH1 PATH2" >&2
        return 1
    fi

    local path1="$1"
    local path2="$2"

    if [ ! -r "$path1" ] || [ ! -w "$path1" ]; then
        echo "${FUNCNAME[0]}: must be a regular file: $path1" >&2
        return 1
    fi

    if [ ! -r "$path2" ] || [ ! -w "$path2" ]; then
        echo "${FUNCNAME[0]}: must be a regular file: $path2" >&2
        return 1
    fi

    local path1_dir
    path1_dir="$( dirname -- "$path1" )"

    local tmp_path
    tmp_path="$( mktemp -- "$path1_dir/XXX" )"

    mv -- "$path1" "$tmp_path"
    mv -- "$path2" "$path1"
    mv -- "$tmp_path" "$path2"
)