Useful bash scripts

Just some personally useful bash scripts:

Find and delete files using a pattern

Find all files containing a particular string and do something with them - in this case, delete all files like "._*" i.e. "._user.module". This is usually junk left over from dead SSH sessions

for FILE in $(find . | grep '\._');
  do
  rm $FILE;
done;

Extract and import dumped SQL

This one comes from my work on gamerswithjobs.com, where I frequently received database dumps in the form of table dumps and need to decompress the import the SQL into a local DB. Also useful for bulk archiving or decompressing a large number of files.

echo "Extracting archives...";
for FILE in `ls *.gz`;
  do
  echo "Extracting $FILE ...";
  gzip -d $FILE;
done;

echo "Importing SQL...";
for FILE in `ls *.sql`;
  do
  echo "Importing $FILE ...";
  mysql -h dbhost -u dbuser -pdbpass dbname < $FILE;
done;

Dump and compress database tables

Another useful one from gamerswithjobs.com work. This one dump each table from a database as an individual .sql file. This is particularly useful for extremely large databases where a straight dump of the entire DB would take longer than acceptable, either by potential crashes or by sys admin enforcement of a max execution time of commands.

echo "Dumping tables...";
for TBL in `mysql -e "show tables" -N -h dbhost -u dbuser -pdbpass dbname`;
  do
  echo "Dumping $TBL";
  mysqldump -h dbhost -u dbuser -pdbpass dbname $TBL > $TBL.sql;
done;

echo "Compressing dumped tables...";
for FILE in `ls *.sql`;
  do
  echo "Compressing $FILE ...";
  gzip $FILE;
done;

Comments

No need to use grep or a for loop for that first task on most systems, find can do it all for you...
find . -name '._*' -exec rm {} \;
or if you want confirmation on before delete (better safe than sorry)...
find . -name '._*' -ok rm {} \;

The others could be condensed and made a little more fool-proof as well, but I'm sure work well enough when used in very specific circumstances. But then, whatever works, right? The shell gives you lots of ways to do everything.

Ah, slick - thanks for that tip. While I've been fumbling around the Unix command line for a few years now, there are still some basic things I'm trying to catch up on.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • Twitter-style @usersnames are linked to their Twitter account pages.
  • Twitter-style #hashtags are linked to search.twitter.com.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.