Tag Archives: Shell

Shell script: recursive find/replace

Lately I had a requirement of finding & replacing a specific string from all the files under a directory tree, while keeping the file permissions intact. Here is the shell script that I eventually came up..

#!/bin/bash

cd target_dir

for _file in `find .`;
do
  if [ ! -d $_file ]; then
    sed "s/SEARCH_STR/REPLACE_STR/g" $_file > tmp; cp tmp $_file; rm tmp;
  fi
done

Hope this would help somebody.. disfrutar!

Shell: test: argument expected

The following shell script might work just fine on many of the available shell interpreters but the same would fail with the ‘test: argument expected’ error if you try to execute it under sh on Solaris platform.

#!/usr/bin/sh

touch /tmp/i_exist
if [ -e /tmp/i_exist ]; then
  echo "file exists!"
fi

So, what we are trying in the above script is to check if the given file exists using shell’s [condition].
As per Solaris test(1):


-e file — True if file exists. (Not available in sh.)

A simple solution to this issue is to use ‘-f’ instead. It checks for the existence of regular files and supposed to work on most of existing shell interpreters.