Shell script time-savers are handy. Why? They give you time to focus on important things rather than tedious yak shaving. The time it takes to write a little script is hardly anything compared to the time it saves.
Say yes to everything
Who would have thought that a command that simply echoes “y” (or whatever you want) in a loop would come in so handy? But it turns out that automating scripts is hard because they often expect interaction from a human user. Now you can get past those pesky “Do you accept this license?” or “are you sure?” questions simply by piping in the
$ yes | ./install.sh
To have it echo something else than “y” simply pass the string you want as a parameter:
$ yes 1 | ./choosewisely.sh
$ yes "I know you are but what am I"
Run a command as another user
Sometimes you want to run a command as someone else. Maybe (for instance) you want to not care who ran a script, you still want any files touched or directories made to be made by a specific user. You can specify the user you want to execute the given command using the sudo command option “-u”, but I always add “-i” also in case there’s any user-specific options I want to pick up. (Read the man page about -i if you’re interested.)
$ sudo -i -u webapp mkdir /webapps
Get the script’s file name
OK here’s another one that sounds dumb at first (like ‘yes’ above) but actually comes in very handy. You can get the name of the script that you’re in using:
Why is this useful? Well besides amusing things like being able to have a script delete itself, you can have the script copy itself somewhere else, which is how I’ve used it before.
Clear bash history
Uh oh! Someone (a “friend” right?) passed their password in clear-text as a parameter on the command line. What can you do now? It’s in the history forever, right?
You read some things and try:
$ history -c
Hey looks like it’s gone! Yay!
But the next time you close out and open the shell, boom! There it is again!
Instead, you need to do:
$ history -c $ history -w
The “history -w” overwrites the .bash_history file with the history in the current shell. Phew!
As always, have fun cutting out the yak shaving and I’m sure I’ll be back with another installment soon!