Bash script using default value for empty parameter

Problem

You have a bash script that accepts parameter(s) but you want to give a default value for a missing parameter.

Solution

For example you have a script that accepts a parameter with the year and month (ie 201703), but you want to give it a default of two months ago if the parameter is missing.

#!/bin/bash

LM=$(date -d '2 month ago' +%Y%m)
YEARMONTH=${1:-${LM}}
echo $YEARMONTH

Remove line from bash history

Problem

You want to remove a certain line from your server’s bash history, if for example you pasted a password in the wrong place.

Solution

Use the two steps:

1. history -d line_number to remove from memory
2. history -w to write in-memory history to the history file ~/.bash_history

as described here

When the shell is not bash (sh) you can remove them from ~/.ash_history and then source the file.

Password – less logins and aliases with ssh

Problem
You want to be able to login to different servers with ssh, but don’t want to be using your password every time.

Solution
We assume that you already have installed ssh and have created ssh public keys in your local machine.

  1. Run the following in your local machine:
    ssh-copy-id -i ~/.ssh/id_rsa.pub user_name@remote_host
  2. If you want to add aliases in your bash profile so you don’t have to type the whole address of the remote host, edit your .bashrc and add:
    alias short_name="ssh user_name@remote_host"
  3. Restart your X server, or simply start a new terminal session
  4. You should be able to login with ssh without using your password by typing in your command prompt in your local machine:
    short_name