SoCoder -> Snippet Home -> Misc
Created : 24 November 2019
Edited : 24 November 2019
System : Linux
Language : shell script
contains.sh - check if pattern exists in file, append line to file
Shell Utils github repo
I needed to programatically ensure my /etc/hosts file contained a certain line, and add it if it wasn't there.
So I polished off a robust shell script to do this: contains.sh
It's a simple script, but carefully designed to do the right thing.
./contains.sh - check if pattern exists in file, append line to file.
./contains.sh PATH PATTERN [ADDITION [USER]
Searches the file at PATH for a string matching the regular expression
Appends ADDITION to PATH if PATTERN is not found, optionally as USER.
zero/true iff PATH contains a line matching PATTERN.
This command makes writes atomically while preserving file permissions and ownership. If another command simultaneously writes to PATH then it is possible that update will be lost.
Ben Golightly <firstname.lastname@example.org>
Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty.
|Sunday, 24 November 2019, 06:38|
That looks handy.
I'm not sure I'd trust my lack of regex skills not to end up completely buggering up all my files, though!
I swear, every time I think I'm getting the hang of it, turns out everything I thought I knew was down to an absolute fluke of something actually working properly that one time!