| 1 | #! /bin/bash |
| 2 | |
| 3 | # fai-sed, call sed with diff before writing |
| 4 | # |
| 5 | # (c) Thomas Lange 2019-2025 [email protected] |
| 6 | # |
| 7 | |
| 8 | # idempotent sed. Execute sed command on a file |
| 9 | # but do not overwrite file if nothing has changed |
| 10 | |
| 11 | dryrun=0 |
| 12 | showchanged=0 |
| 13 | |
| 14 | while getopts nE opt ; do |
| 15 | case "$opt" in |
| 16 | E) showchanged=1 ;; |
| 17 | n) dryrun=1 ;; |
| 18 | esac |
| 19 | done |
| 20 | shift $((OPTIND - 1)) |
| 21 | |
| 22 | |
| 23 | cmd=$1 |
| 24 | shift |
| 25 | filename=$1 |
| 26 | shift |
| 27 | |
| 28 | if [ -z "$cmd" ] || [ -z "$filename" ]; then |
| 29 | printf "Please add filename and sed command\n" |
| 30 | exit 3 |
| 31 | fi |
| 32 | |
| 33 | # do not allow more than one file |
| 34 | if [ -n "$1" ]; then |
| 35 | printf "Aborting. Too many arguments.\n" |
| 36 | exit 5 |
| 37 | fi |
| 38 | |
| 39 | if [ -n "$target" ]; then |
| 40 | filename="$target$filename" |
| 41 | fi |
| 42 | |
| 43 | if [ ! -f $filename ]; then |
| 44 | printf "WARNING: $filename does not exists. Skipping\n" |
| 45 | exit 0 |
| 46 | fi |
| 47 | |
| 48 | tmp=$(mktemp) |
| 49 | trap "rm $tmp" EXIT |
| 50 | |
| 51 | printf "sed -e $cmd $filename: " |
| 52 | # cp file so we can use sed -i, otherwise the new file created by sed has different chmod, owner |
| 53 | cp -p $filename $tmp |
| 54 | sed -i -e "$cmd" $tmp |
| 55 | res=$? |
| 56 | if [ $res -ne 0 ]; then |
| 57 | printf "sed error $res\n" |
| 58 | exit $res |
| 59 | fi |
| 60 | |
| 61 | cmp -s $filename $tmp |
| 62 | res=$? |
| 63 | if [ $res -eq 0 ]; then |
| 64 | printf " No changes.\n" |
| 65 | exit 0 |
| 66 | fi |
| 67 | |
| 68 | if [ $res -eq 1 ]; then |
| 69 | if [ $dryrun -eq 1 ]; then |
| 70 | printf " Dry-run. Changes not applied.\n" |
| 71 | exit 0 |
| 72 | fi |
| 73 | mv $tmp $filename |
| 74 | printf " File changed.\n" |
| 75 | trap '' EXIT |
| 76 | if [ $showchanged -eq 1 ]; then |
| 77 | exit 9 |
| 78 | fi |
| 79 | exit 0 |
| 80 | fi |
| 81 | |
| 82 | if [ $res -eq 2 ]; then |
| 83 | printf " diff error $res. No changes made to $filename\n" |
| 84 | exit 2 |
| 85 | fi |