Bash shell tricks

The bash shell has so many nifty tricks. They can come in handy in order to save time with repeated tasks, recover data, etc.

  1. My set of customizations for bash can be found on github. With those customizations, you can make find easier, colorize diff, man and prevent clobbering when using output redirection. I especially love the colored man pages.

  2. If you want to sudo-ize the previous command, use;

sudo !!
  1. rename utility: I never knew this! It makes renaming multiple files using regex patterns so much easier!

  2. In scripts, instead of the awkward test command ‘[‘, use ‘(( … ))’ and ‘[[ … ]]’ in its place. It makes logical and string comparison so much easier. (ref: modern bash test operators)

  3. To get your current shell name, do

ps -p $$

or

echo $0

 

Some more examples can be found here: bash trick commands

There are also some intricacies like the difference between rm and unlinkrm vs unlink

Feel free to suggest more in your comments.

Note: The file .bashrc is not loaded by bash at startup, by default. So it must be included in either the file .profile or .bash_profile.

ssh tricks

I must have used ssh for the past 15 years but I never knew this trick. So if you want to ssh into a remote server and run some command on it, and exit, you don’t actually need to login into the console and type the commands. It can be done by injecting commands through a ssh connection (and piping the output back too).

So if you want to ssh into the raspberry pi and do a simple ‘ls’, use this:

ssh  pi@host -p port#  'ls'

If you use key authentication and have saved the keys, your login can be automated without the need for password (more on that later).

If you’d like to get the output and store it on the local host, use regular linux redirection:

ssh  pi@host -p port# 'ls' > test.txt

Isn’t this great 🙂

More details can be found here:

Run commands through ssh

Pipe output from local to remote server using ssh

Securing secure-shell server

Credit:random

A follow-up to my earlier post about securing access to your RPi. (fail2ban-lifesaver). Some amount of security can indeed be obtained through obscurity. One way to do this is to change the default port # for the ssh server. Since most hackers will try to attack port 22 first, it’ll take some time to reach the obscure port number set by you on your RPi. Yes port scanning will eventually find it, but hey, why not delay the attack 🙂

#Port 22
Port 16022

Read up about how to change the default ssh server port here (its really quite simple): Change default ssh port.

Also remember to change it in the fail2ban config file.

#port = ssh
port = 16022

Further security measures like public key, port knocking: Harden the ssh server.

I also used iptables to block a whole range of IP addresses, from which hackers are trying to attack my RPi. This is how you do it: Block a range of IP addresses.

sudo iptables -I INPUT -s 103.0.0.0/8 -j DROP