Delete all but the most recent X files in bash

The problems with the existing answers: inability to handle filenames with embedded spaces or newlines. in the case of solutions that invoke rm directly on an unquoted command substitution (rm `…`), there’s an added risk of unintended globbing. inability to distinguish between files and directories (i.e., if directories happened to be among the 5 most … Read more

How do I abort the execution of a Python script? [duplicate]

To exit a script you can use, import sys sys.exit() You can also provide an exit status value, usually an integer. import sys sys.exit(0) Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero. import sys sys.exit(“aa! errors!”) Prints “aa! errors!” and … Read more

How to get the part of a file after the first line that matches a regular expression

The following will print the line matching TERMINATE till the end of the file: sed -n -e ‘/TERMINATE/,$p’ Explained: -n disables default behavior of sed of printing each line after executing its script on it, -e indicated a script to sed, /TERMINATE/,$ is an address (line) range selection meaning the first line matching the TERMINATE … Read more

Wait for a process to finish

To wait for any process to finish Linux (doesn’t work on Alpine, where ash doesn’t support tail –pid): tail –pid=$pid -f /dev/null Darwin (requires that $pid has open files): lsof -p $pid +r 1 &>/dev/null With timeout (seconds) Linux: timeout $timeout tail –pid=$pid -f /dev/null Darwin (requires that $pid has open files): lsof -p $pid … Read more