Automate everything (practical uses of Bash part 3)

Last time I provided some quick shell script time-savers. The goal of automation is saving time and providing 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.

List folders by size

du -h --max-depth=1 | sort -h

Executing this handy command gives you a list of all the folders in the current directory and their size, sorted from least to greatest.

Read user input
Here’s one way to read user input.

Save the following to

echo "What is your name?"
read name
echo "Hello $name"

Running this script should give output like this:

$ ./ 
What is your name?
Hello Scott


Read passwords
You can use the -s flag on the read command for sensitive stuff like passwords.

Save the following to

echo -n "Username: "
read username
echo -n "Password: "
read -s password

The output from this should look like this:

$ ./ 
Username: scottshi

Because of the -s flag the characters entered for the password line won’t display.

Verify user input
You can combine the above with standard string comparison to make sure that users entered the right thing. For example, let’s say you are going to prompt someone for their Maven repository username and password, and save the result in the users Maven settings. I won’t go over the save part of that, but it will be nice to your users if you verify that they have entered the same password twice.

Try this in a file called

echo -n "Username: "
  read mvnusername
  echo -n "Password: "
  read -s mvnpassword
  echo -en "\nRepeat password: "
  read -s mvnpassword2
  echo -e "\n"
  if [ "$mvnpassword" != "$mvnpassword2" ]; then
    echo "Sorry you entered two unmatching passwords."
    echo "Cannot continue! Exiting!"
    exit 1

Find files or folder from a certain year
This is an easy way to find files or folders from a certain year, assuming your ls -l outputs the year. For the example I’m finding everything in 2016 in the current directory.

ls -l | grep 2016

If you want just the file or folder name, you can add an awk statement to parse just that.

ls -l | grep 2016 | awk -F " " '{print $9}'

Loop over files and do something to them
For example, let’s say you want to use the above to find all the files from 2016 and move them to a folder you’ve created called 2016.

ls -l | grep 2016 | awk -F " " '{print $9}' | while read filename; do mv $filename 2016/; done

Have fun cutting out the yak shaving and I’m sure I’ll be back with another installment soon!

One thought on “Automate everything (practical uses of Bash part 3)

Leave a Reply

Your email address will not be published. Required fields are marked *