JBY Technologies

Writing And Running Bash Scripts At The Prompt

A really cool thing about the bash shell is that you can write automated tasks at the prompt and run them right there as well.

Here is an example of some steps I do to ensure users are running the appropriate versions of the .bash_profile and .bashrc scripts when I migrate users to a newer version of Redhat or Centos. Login scripts on other Linux flavors, Ubuntu for example, may be named slightly different, but the same concept works with Bash there as well.

I would first copy all the user home directories from the old system to the /home directory on the new system.

Then run this...

# cd /home
# unalias ls cp
# for uzer in `ls`
# do
# if [ -s "$uzer/.bash_profile" ]
# then
# INI=`grep INI $uzer/.bash_profile`
# EXE=`grep MNU $uzer/.bash_profile`
# cp -f /etc/skel/.bash_profile $uzer
# cp -f /etc/skel/.bashrc $uzer
# echo $INI >> $uzer/.bash_profile
# echo $EXE >> $uzer/.bash_profile
# fi
# done

Enter after each line. Bash determines from your syntax when your job is runnable. The closing fi and done tell Bash that in this case.

The job is checking the old login scripts copied over from a previous Redhat version for directives I want to preserve, and appending those directives to the the new login scripts, which the job then replaces in each user's home directory.

For anyone unfamiliar with Bash scripting, the EXE and INI to the left of the '=' are variables. By prepending the '$' to those later, I can see the values assigned to them. By surrounding the ls command with backquotes, which replace the command with it's results, I am creating a set of strings. I am using a for loop to iterate through the set of strings to confirm that each string is a directory name and the directory contains a .bash_profile file. Then using grep commands to collect the directives I want from the old login script, replace the old login scripts with the new ones, and echo the values of my variables to append the directives to the new login scripts.

I started doing this, by the way, a few years ago after I noticed that users would sometimes get grep errors as a result of an empty value being grepped for at login. Keeping the login scripts current with the Bash release solves that problem.

If you up arrow a time or two, or type "history", you can copy your cli generated script and save it for future use. Just paste it in a file. It you prefer it to look "flock of geese", you can delete the semi colons added by bash and replace them with newlines and indentation.

Bookmark and Share

Legal Notices