Check if a file or directory exists with bash
This script tests if nginx exists and is executable. The script prints a warning and exits, if nginx doesn’t exists or isn’t executable:
1 DAEMON=/usr/local/sbin/nbinx 2 if [ ! -x $DAEMON ] 3 then 4 echo "Couldn't find $DAEMON. Please set path to DAEMON." 5 exit 0 6 fi
See man test for more information on how to use the test command.
Appending after a pattern from a file in sed
Useful when you want to append the contents of a whole file into something you are sed’ing. Be careful if you use -i, it will replace the working file.
1 sed -i "/attr_accessor :config/r ../patch_for_application.rb.tmpl" app/controllers/application.rb
Automatically giving predetermined answers to a program.
Sometimes you want to automate the running of a script or program, but the darn thing keeps asking questions and expects interactive answers. Shell scripting makes it easy to give the answers automatically, using a stream redirection from a file.
1 ./qurious_program < predetermined_answers.txt
Colorize grep
Put this export in .bashrc to make grep colorize the text it found.
1 export GREP_OPTIONS='--color=auto'
Bulk renaming of files
Rename the files in a directory by replacing a space with an underscore. The rename program comes with most modern Linux distros.
1 rename 's/\ /_/g' *.*