-=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- (c) WidthPadding Industries 1987 0|345|0 -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=-
SoCoder -> Snippet Home -> Misc


 
HoboBen
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



contains.sh
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.


NAME

./contains.sh - check if pattern exists in file, append line to file.

SYNOPSIS

./contains.sh PATH PATTERN [ADDITION [USER]
./contains.sh version

DESCRIPTION

Searches the file at PATH for a string matching the regular expression
PATTERN.

Appends ADDITION to PATH if PATTERN is not found, optionally as USER.

ARGUMENTS

  • PATH
    Path to the file to search.
  • PATTERN
    Grep-style extended regular expression: see `man 1 grep` for syntax.
  • ADDITION (optional)
    String to append to the file.
  • USER (optional)
    If present, the file is updated as the specified USER e.g. root.

RETURNS

zero/true iff PATH contains a line matching PATTERN.

EXAMPLES

  • Do something if a given string exists anywhere in a file:


  • Do something if any line in a file ends in a file extension:


  • Update /etc/hosts if an exact entry doesn't exist:


  • (Safer) Update /etc/hosts as root if an exact entry doesn't exist:


CONCURRENCY

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.

AUTHOR

Ben Golightly <ben@tawesoft.co.uk>

COPYING

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.

 

Comments


Sunday, 24 November 2019, 06:38
Jayenkai
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!