Link Menu Search Expand Document

Bash & Shellscript

Table of contents

  1. Shellscript
    1. Infinite loop
    2. Syntax: if
    3. Loop through lines of a file
    4. Get number of arguments for script
    5. Get formatted date
  2. Keyboard Cursor Movements
  3. Terminal stuff
    1. Change terminal window title

Shellscript

This section covers some shellscript stuff that I keep forgetting. Mostly quick snippets for simple things.

Infinite loop

while :; do
    echo "This is infinite!"
    sleep 5
done

Syntax: if

if [ ! -d "/tmp" ]; then
    echo "Directory /tmp does not exist"
else
    echo "It exists!"
fi

If we want to compare numbers:

x=10
if [[ 10 = $x ]]; then
    echo "x is ten!"
fi

Loop through lines of a file

#!/bin/bash

while read line; do
    echo "Line = $line"
done; < your_file.txt

Get number of arguments for script

echo "Script received $# args"

if [[ $# < 2 ]]; then
  echo "Expected at least 2 arguments to the script"
  exit -1
fi

Get formatted date

now=$(date +"%Y.%m.%d %H:%M:%S")
echo $now

This returns:

2020.03.31 20:02:05

Keyboard Cursor Movements

  • ctrl-a - move the cursor to the beginning of the current line
  • ctrl-e - move the cursor to the end of the current line
  • alt-b - move the cursor backwards one word
  • alt-f - move the cursor forward one word
  • ctrl-k - delete from cursor to the end of the line
  • ctrl-u - delete from cursor to the beginning of the line
  • alt-d - delete the word in front of the cursor
  • ctrl-w - delete the word behind of the cursor

Terminal stuff

Not sure where to put this, so I put it here for now.

Change terminal window title

In your terminal do this:

echo -e "\e]0;Your title here\a"

This response on i3’s FAQ/Stackoverflow thingy gives some other ideas as well.


Gilgalab Knowledge Base