Bash xargs – Use Anywhere in Your Command

If you want to use the xargs command to build a new command and place the standard input from your stream wherever you like (or in multiple places), here is an example:

Let’s say we have a hosts file:

111.222.111.222 host1.mydomain.com
222.111.222.111 host2.mydomain.com

We can take out the first column with awk (the IP column), and we can pipe it to xargs and use -I. Then we can use the % sign to both ssh to the IP and to display a message with the IP written from the host.

This is obviously very flexible and useful for pretty much any command you’re building from earlier inputs :).

cat dynamic_hosts | awk '{print $1}' | xargs -I % ssh % "echo hi from %"

Use wget with self-signed certificate and output to stdout

Not much of an article here… but if you want to use WGET to validate a spring boot app with a self-signed certificate, for example, and you don’t want to bother outputting the results to file, you can do this:

wget -q -O – https://172.20.234.165/actuator/health –no-check-certificate

The output would be right inline and would avoid the certificate validation:

# wget -q -O – https://172.20.234.165/actuator/health –no-check-certificate
{“status”:”UP”} #

You could achieve this with curl as well I’m sure – but it isn’t installed on alpine it seems and I didn’t want to install extra tools.

 

Bash – Grep (or Run Other Command) Only On Files Created This Week, Day.

Use Case

I just ran into a simple problem where I had to grep files on a server, but the directory had TONS and TONS of files in it.  I just wanted to target files created within the last week or so.

Working Command

It turns out this find command is very handy for this occasion.  It was taken and lightly modified from this unix stack-exchange post after a fair bit of searching.

find . -mtime -7 -exec grep "my_search_string" {} \;

Basically, it finds everything in “.” (the current directory) that was created in the last 7 days (as in 24 hour days, not from-this-morning days), and it executes the grep expression on it.

You can modify the timing however you want with mtime as well as change the target directory or command to execute, and of course you can pipe the output to whatever you want :).