-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathappend
80 lines (70 loc) · 2.61 KB
/
append
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/bin/bash
# append string, file, stdin to file & avoid doubles
# default options
to_array RPI_APPEND_FILE
to_array RPI_APPEND_APPENDIX
function rpi_append_prerun() {
# check arguments
[[ -n "${RPI_APPEND_FILE}" ]] || error "RPI_APPEND_FILE unset. appending to unknown file"
[[ -n "${RPI_APPEND_APPENDIX}" ]] || error "RPI_APPEND_APPENDIX unset. nothing to append."s
}
function rpi_append_run() {
local i
local file
local appendix
local string
# append file to file ?
i=0
for appendix in "${RPI_APPEND_APPENDIX[@]}" ; do
file="${RPI_APPEND_FILE["${i}"]}"
# appendix is path to file?
if [[ -f "${appendix}" ]] ; then
rpi_append_file_to_file "${appendix}" "${file}" || error "rpi_append_file_to_file ${appendix} ${file}"
# appendix is string
else
rpi_append_to_file "${appendix}" "${file}" || error "rpi_append_to_file ${appendix} ${file}"
fi
i+=1
done
}
function rpi_append_description() {
echo "append string, file, stdin to file & avoid doubles"
}
function rpi_append_help_params() {
help_param "RPI_APPEND_FILE" "the file to append to"
help_param "RPI_APPEND_APPENDIX" "string or file which contents should be appended"
}
# ---------------------------------------------------------------------
# append file to file
function rpi_append_file_to_file() {
local appendix="$1"
local appendee="$2"
if [[ -z "${appendix}" ]] || [[ -z "${appendee}" ]] ; then error "missing argument. append" ; fi
# already appended ?
[[ -f "${appendix}" ]] && [[ -f "${appendee}" ]] && grep --quiet --fixed-strings --file="${appendix}" "${appendee}" && return 0
# shellcheck disable=SC2024
# (sudo is only meant for tee, not redirect)
# append
sudo tee -a "${appendee}" < "${appendix}" >/dev/null || error "sudo_append ${appendix} ${appendee}"
}
# append string to file
function rpi_append_to_file() {
local string="$1"
local file="$2"
if [[ -z "${string}" ]] || [[ -z "${file}" ]] ; then error "missing argument. append" ; fi
# already appended ?
[[ -f "${file}" ]] && sudo grep --fixed-strings --quiet "${string}" "${file}" && return 0
# append
sudo touch "${file}"
printf "%s\n" "${string}" | sudo tee -a "${file}" >/dev/null || error "sudo_append ${string} ${file}"
verbose "appended \"${string}\" to \"${file}\""
}
# append input from stdin to file
function rpi_append_stdin() {
local file="$1"
[[ -n "${file}" ]] || error "missing argument. append_stdin"
IFS=''
while read -r appendix ; do
rpi_append_to_file "${appendix}" "${file}"
done
}