05 January 2011

BASH TETRIS

This one is a pure bash tetris game.
Surprisingly working beyond all expectations.







#!/bin/bash
# Tetris Game 
# 10.21.2003 xhchen 
# http://read.pudn.com/downloads99/sourcecode/game/404711/tetris.sh__.htm
# Copyright (C) xhchen
#color definition 
cRed=1 
cGreen=2 
cYellow=3 
cBlue=4 
cFuchsia=5 
cCyan=6 
cWhite=7 
colorTable=($cRed $cGreen $cYellow $cBlue $cFuchsia $cCyan $cWhite) 
#size & position 
iLeft=3 
iTop=2 
((iTrayLeft = iLeft + 2)) 
((iTrayTop = iTop + 1)) 
((iTrayWidth = 10)) 
((iTrayHeight = 15)) 
#style definition 
cBorder=$cGreen 
cScore=$cFuchsia 
cScoreValue=$cCyan 
#control signal 
sigRotate=25 
sigLeft=26 
sigRight=27 
sigDown=28 
sigAllDown=29 
sigExit=30 
#boxes
box0=(0 0 0 1 1 0 1 1) 
box1=(0 2 1 2 2 2 3 2 1 0 1 1 1 2 1 3) 
box2=(0 0 0 1 1 1 1 2 0 1 1 0 1 1 2 0) 
box3=(0 1 0 2 1 0 1 1 0 0 1 0 1 1 2 1) 
box4=(0 1 0 2 1 1 2 1 1 0 1 1 1 2 2 2 0 1 1 1 2 0 2 1 0 0 1 0 1 1 1 2) 
box5=(0 1 1 1 2 1 2 2 1 0 1 1 1 2 2 0 0 0 0 1 1 1 2 1 0 2 1 0 1 1 1 2) 
box6=(0 1 1 1 1 2 2 1 1 0 1 1 1 2 2 1 0 1 1 0 1 1 2 1 0 1 1 0 1 1 1 2) 
box=(${box0[@]} ${box1[@]} ${box2[@]} ${box3[@]} ${box4[@]} ${box5[@]} ${box6[@]}) 
countBox=(1 2 2 2 4 4 4 ) 
offsetBox=(0 1 3 5 7 11 15) 
#score
iScoreEachLevel=50   #be greater than 7 
#Runtime data 
sig=0 
iScore=0 
iLevel=0 
boxNew=()         #new box 
cBoxNew=0         #new box color 
iBoxNewType=0     #new box type 
iBoxNewRotate=0   #new box rotate degree 
boxCur=()         #current box 
cBoxCur=0         #current box color 
iBoxCurType=0     #current box type 
iBoxCurRotate=0   #current box rotate degree 
boxCurX=-1        #current X position 
boxCurY=-1        #current Y position 
iMap=() 
for ((i = 0; i < iTrayHeight * iTrayWidth; i++)); do iMap[$i]=-1; done 
RunAsKeyReceiver() { 
   local pidDisplayer key aKey sig cESC sTTY 
   pidDisplayer=$1 
   aKey=(0 0 0) 
   cESC=`echo -ne "\033"` 
   cSpace=`echo -ne "\040"` 
   sTTY=`stty -g` 
    
   trap "MyExit;" INT TERM 
   trap "MyExitNoSub;" $sigExit 
    
   echo -ne "\033[?25l" 
   while : 
   do 
      read -s -n 1 key 
      aKey[0]=${aKey[1]} 
      aKey[1]=${aKey[2]} 
      aKey[2]=$key 
      sig=0 
      if [[ $key == $cESC && ${aKey[1]} == $cESC ]] 
      then 
         MyExit 
      elif [[ ${aKey[0]} == $cESC && ${aKey[1]} == "[" ]] 
      then 
         if [[ $key == "A" ]]; then sig=$sigRotate 
         elif [[ $key == "B" ]]; then sig=$sigDown 
         elif [[ $key == "D" ]]; then sig=$sigLeft 
         elif [[ $key == "C" ]]; then sig=$sigRight 
         fi 
      elif [[ $key == "W" || $key == "w" ]]; then sig=$sigRotate 
      elif [[ $key == "S" || $key == "s" ]]; then sig=$sigDown 
      elif [[ $key == "A" || $key == "a" ]]; then sig=$sigLeft 
      elif [[ $key == "D" || $key == "d" ]]; then sig=$sigRight 
      elif [[ "[$key]" == "[]" ]]; then sig=$sigAllDown 
      elif [[ $key == "Q" || $key == "q" ]] 
      then 
         MyExit 
      fi 
      if [[ $sig != 0 ]] 
      then 
         kill -$sig $pidDisplayer 
      fi 
   done 
} 
MyExitNoSub(){ 
   local y 
   stty $sTTY 
   ((y = iTop + iTrayHeight + 4)) 
   echo -e "\033[?25h\033[${y};0H" 
   exit 
} 
MyExit(){ 
   kill -$sigExit $pidDisplayer 
   MyExitNoSub 
} 
RunAsDisplayer(){ 
   local sigThis 
   InitDraw 
   trap "sig=$sigRotate;" $sigRotate 
   trap "sig=$sigLeft;" $sigLeft 
   trap "sig=$sigRight;" $sigRight 
   trap "sig=$sigDown;" $sigDown 
   trap "sig=$sigAllDown;" $sigAllDown 
   trap "ShowExit;" $sigExit 
   while :
   do 
      for ((i = 0; i < 21 - iLevel; i++)) 
      do 
         usleep 20000 
         sigThis=$sig 
         sig=0 
         if ((sigThis == sigRotate)); then BoxRotate; 
         elif ((sigThis == sigLeft)); then BoxLeft; 
         elif ((sigThis == sigRight)); then BoxRight; 
         elif ((sigThis == sigDown)); then BoxDown; 
         elif ((sigThis == sigAllDown)); then BoxAllDown; 
         fi 
      done 
      #kill -$sigDown $$ 
      BoxDown 
   done 
} 
BoxMove(){
   local j i x y xTest yTest 
   yTest=$1 
   xTest=$2 
   for ((j = 0; j < 8; j += 2)) 
   do 
      ((i = j + 1)) 
      ((y = ${boxCur[$j]} + yTest)) 
      ((x = ${boxCur[$i]} + xTest)) 
      if (( y < 0 || y >= iTrayHeight || x < 0 || x >= iTrayWidth)) 
      then 
         return 1 
      fi 
      if ((${iMap[y * iTrayWidth + x]} != -1 )) 
      then 
         return 1 
      fi 
   done 
   return 0; 
} 
Box2Map(){ 
   local j i x y xp yp line 
   for ((j = 0; j < 8; j += 2)) 
   do 
      ((i = j + 1)) 
      ((y = ${boxCur[$j]} + boxCurY)) 
      ((x = ${boxCur[$i]} + boxCurX)) 
      ((i = y * iTrayWidth + x)) 
      iMap[$i]=$cBoxCur 
   done 
   line=0 
   for ((j = 0; j < iTrayWidth * iTrayHeight; j += iTrayWidth)) 
   do 
      for ((i = j + iTrayWidth - 1; i >= j; i--)) 
      do 
         if ((${iMap[$i]} == -1)); then break; fi 
      done 
      if ((i >= j)); then continue; fi 
    
      ((line++))    
      for ((i = j - 1; i >= 0; i--)) 
      do 
         ((x = i + iTrayWidth)) 
         iMap[$x]=${iMap[$i]} 
      done 
      for ((i = 0; i < iTrayWidth; i++)) 
      do 
         iMap[$i]=-1 
      done 
   done 
   if ((line == 0)); then return; fi 
   ((x = iLeft + iTrayWidth * 2 + 7)) 
   ((y = iTop + 11)) 
   ((iScore += line * 2 - 1)) 
   echo -ne "\033[1m\033[3${cScoreValue}m\033[${y};${x}H${iScore}         " 
   if ((iScore % iScoreEachLevel < line * 2 - 1)) 
   then 
      if ((iLevel < 20)) 
      then 
         ((iLevel++)) 
         ((y = iTop + 14)) 
         echo -ne "\033[3${cScoreValue}m\033[${y};${x}H${iLevel}        " 
      fi 
   fi 
   echo -ne "\033[0m" 
   for ((y = 0; y < iTrayHeight; y++)) 
   do 
      ((yp = y + iTrayTop + 1)) 
      ((xp = iTrayLeft + 1)) 
      ((i = y * iTrayWidth)) 
      echo -ne "\033[${yp};${xp}H" 
      for ((x = 0; x < iTrayWidth; x++)) 
      do 
         ((j = i + x)) 
         if ((${iMap[$j]} == -1)) 
         then 
            echo -ne "  " 
         else 
            echo -ne "\033[1m\033[7m\033[3${iMap[$j]}m\033[4${iMap[$j]}m\040\040\033[0m" 
         fi 
      done 
   done 
} 
BoxDown(){ 
   local y s 
   ((y = boxCurY + 1)) 
   if BoxMove $y $boxCurX 
   then 
      s="`DrawCurBox 0`" 
      ((boxCurY = y)) 
      s="$s`DrawCurBox 1`" 
      echo -ne $s 
   else 
      Box2Map 
      RandomBox 
   fi 
} 
BoxLeft(){ 
   local x s 
   ((x = boxCurX - 1)) 
   if BoxMove $boxCurY $x 
   then 
      s=`DrawCurBox 0` 
      ((boxCurX = x)) 
      s=$s`DrawCurBox 1` 
      echo -ne $s 
   fi 
} 
BoxRight(){ 
   local x s 
   ((x = boxCurX + 1)) 
   if BoxMove $boxCurY $x 
   then 
      s=`DrawCurBox 0` 
      ((boxCurX = x)) 
      s=$s`DrawCurBox 1` 
      echo -ne $s 
   fi 
} 
BoxAllDown(){ 
   local k j i x y iDown s 
   iDown=$iTrayHeight 
   for ((j = 0; j < 8; j += 2)) 
   do 
      ((i = j + 1)) 
      ((y = ${boxCur[$j]} + boxCurY)) 
      ((x = ${boxCur[$i]} + boxCurX)) 
      for ((k = y + 1; k < iTrayHeight; k++)) 
      do 
         ((i = k * iTrayWidth + x)) 
         if (( ${iMap[$i]} != -1)); then break; fi 
      done 
      ((k -= y + 1)) 
      if (( $iDown > $k )); then iDown=$k; fi 
   done 
   s=`DrawCurBox 0` 
   ((boxCurY += iDown)) 
   s=$s`DrawCurBox 1` 
   echo -ne $s 
   Box2Map 
   RandomBox 
} 
BoxRotate(){ 
   local iCount iTestRotate boxTest j i s 
   iCount=${countBox[$iBoxCurType]} 
   ((iTestRotate = iBoxCurRotate + 1)) 
   if ((iTestRotate >= iCount)) 
   then 
      ((iTestRotate = 0)) 
   fi 
   for ((j = 0, i = (${offsetBox[$iBoxCurType]} + $iTestRotate) * 8; j < 8; j++, i++)) 
   do 
      boxTest[$j]=${boxCur[$j]} 
      boxCur[$j]=${box[$i]} 
   done 
   if BoxMove $boxCurY $boxCurX 
   then 
      for ((j = 0; j < 8; j++)) 
      do 
         boxCur[$j]=${boxTest[$j]} 
      done 
      s=`DrawCurBox 0` 
      for ((j = 0, i = (${offsetBox[$iBoxCurType]} + $iTestRotate) * 8; j < 8; j++, i++)) 
      do 
         boxCur[$j]=${box[$i]} 
      done 
      s=$s`DrawCurBox 1` 
      echo -ne $s 
      iBoxCurRotate=$iTestRotate 
   else 
      for ((j = 0; j < 8; j++)) 
      do 
         boxCur[$j]=${boxTest[$j]} 
      done 
   fi 
} 
DrawCurBox(){ 
   local i j t bDraw sBox s 
   bDraw=$1 
   s="" 
   if (( bDraw == 0 )) 
   then 
      sBox="\040\040" 
   else 
      sBox="\040\040" 
      s=$s"\033[1m\033[7m\033[3${cBoxCur}m\033[4${cBoxCur}m"       
   fi 
   for ((j = 0; j < 8; j += 2)) 
   do 
      ((i = iTrayTop + 1 + ${boxCur[$j]} + boxCurY)) 
      ((t = iTrayLeft + 1 + 2 * (boxCurX + ${boxCur[$j + 1]}))) 
      s=$s"\033[${i};${t}H${sBox}" 
   done 
   s=$s"\033[0m" 
   echo -n $s 
} 
RandomBox(){ 
   local i j t 
   #change current box 
   iBoxCurType=${iBoxNewType} 
   iBoxCurRotate=${iBoxNewRotate} 
   cBoxCur=${cBoxNew} 
   for ((j = 0; j < ${#boxNew[@]}; j++)) 
   do 
      boxCur[$j]=${boxNew[$j]} 
   done 
   if (( ${#boxCur[@]} == 8 )) 
   then 
      #calculate current box's starting position 
      for ((j = 0, t = 4; j < 8; j += 2)) 
      do 
         if ((${boxCur[$j]} < t)); then t=${boxCur[$j]}; fi 
      done 
      ((boxCurY = -t)) 
      for ((j = 1, i = -4, t = 20; j < 8; j += 2)) 
      do 
         if ((${boxCur[$j]} > i)); then i=${boxCur[$j]}; fi 
         if ((${boxCur[$j]} < t)); then t=${boxCur[$j]}; fi 
      done 
      ((boxCurX = (iTrayWidth - 1 - i - t) / 2)) 
      echo -ne `DrawCurBox 1` 
      if ! BoxMove $boxCurY $boxCurX 
      then 
         kill -$sigExit ${PPID} 
         ShowExit 
      fi 
   fi 
   #clear old box 
   for ((j = 0; j < 4; j++)) 
   do 
      ((i = iTop + 1 + j)) 
      ((t = iLeft + 2 * iTrayWidth + 7)) 
      echo -ne "\033[${i};${t}H        " 
   done 
   #get a random new box 
   ((iBoxNewType = RANDOM % ${#offsetBox[@]})) 
   ((iBoxNewRotate = RANDOM % ${countBox[$iBoxNewType]})) 
   for ((j = 0, i = (${offsetBox[$iBoxNewType]} + $iBoxNewRotate) * 8; j < 8; j++, i++)) 
   do 
      boxNew[$j]=${box[$i]}; 
   done 
   ((cBoxNew = ${colorTable[RANDOM % ${#colorTable[@]}]})) 
   #display new box 
   echo -ne "\033[1m\033[7m\033[3${cBoxNew}m\033[4${cBoxNew}m" 
   for ((j = 0; j < 8; j += 2)) 
   do 
      ((i = iTop + 1 + ${boxNew[$j]})) 
      ((t = iLeft + 2 * iTrayWidth + 7 + 2 * ${boxNew[$j + 1]})) 
      echo -ne "\033[${i};${t}H\040\040" 
   done 
   echo -ne "\033[0m" 
} 
InitDraw(){ 
   clear 
   RandomBox 
   RandomBox 
   local i t1 t2 t3 
   #draw border 
   echo -ne "\033[1m" 
   echo -ne "\033[3${cBorder}m\033[4${cBorder}m" 
   ((t2 = iLeft + 1)) 
   ((t3 = iLeft + iTrayWidth * 2 + 3)) 
   for ((i = 0; i < iTrayHeight; i++)) 
   do 
      ((t1 = i + iTop + 2)) 
      echo -ne "\033[${t1};${t2}H\040\040" 
      echo -ne "\033[${t1};${t3}H\040\040" 
   done 
   ((t2 = iTop + iTrayHeight + 2)) 
   for ((i = 0; i < iTrayWidth + 2; i++)) 
   do 
      ((t1 = i * 2 + iLeft + 1)) 
      echo -ne "\033[${iTrayTop};${t1}H\040\040" 
      echo -ne "\033[${t2};${t1}H\040\040" 
   done 
   echo -ne "\033[0m" 
   #draw score & level prompt 
   echo -ne "\033[1m" 
   ((t1 = iLeft + iTrayWidth * 2 + 7)) 
   ((t2 = iTop + 10)) 
   echo -ne "\033[3${cScore}m\033[${t2};${t1}HScore" 
   ((t2 = iTop + 11)) 
   echo -ne "\033[3${cScoreValue}m\033[${t2};${t1}H${iScore}" 
   ((t2 = iTop + 13)) 
   echo -ne "\033[3${cScore}m\033[${t2};${t1}HLevel" 
   ((t2 = iTop + 14)) 
   echo -ne "\033[3${cScoreValue}m\033[${t2};${t1}H${iLevel}" 
   echo -ne "\033[0m" 
} 
ShowExit(){ 
   local y 
   ((y = iTrayHeight + iTrayTop + 3)) 
   echo -e "\033[${y};0HGameOver!\033[0m" 
   exit 
} 
#Start from here. 
if [[ $1 != "--go" ]] 
then 
  $0 --go& 
  RunAsKeyReceiver $! 
  exit 
else 
   RunAsDisplayer 
   exit 
fi 


BASH GAMES: Bash Invaders






Below is the script I have found when trying to manage asynchronous call under bash.
Use J K L keys to navigate and shoot.



#!/bin/bash
if [[ $1 != "" ]]
then
cat << END
BashInvaders!
by Vidar 'koala_man' Holen
www.vidarholen.net

Originally an entry in the #linux.no 1KiB compo (thus the ugly source)
This is a pre-trim version with colors and proper tmp files. All bash. 
Released under the GNU General Public License.

Control your ship with J and L, shoot with K. 
Quit with Q or sigint.

Requires mktemp and sleep with fractions. 

END
exit 0
fi

tput civis

cd /tmp
e=echo
c=clear
r=return
E="$e -ne "
A=$E\\033[
m() { $A$2\;$1\H
}
f() { $A\1\;3$2\m
}

trap z=SigInt SIGINT
 g() {
 $e ${K[$(($2*8+$1))]}
}
 s() {
 K[$(($2*8+$1))]=$3
}
 u() {
 [ $T = 0 ] && $r 0
 m $S $((--T))
 $E `f 3`"."
 x=$((S-Y))
 y=$((T-Z))
 [ $((y%3)) = 0 -a $((x%6)) -lt 4 ] || $r 0
 : $((y/=3)) $((x/=6))
 [ "`g $x $y`" = 1 -a $x -le $o -a $x -ge $n -a $y -le $q -a $y -ge 0 ] || $r 0
 [ $Q = 1 ] && z="You win!"
 s $x $y 0 
 : $((Q--))
 T=0
 $r 1
}
 a() {
 w n +
 w o - 
 h 
}
 w() {
 d=0
 for (( I=0; I<=q; I++ )) {
  [ `g $(($1)) $I` = 1 ] && D=1
 }
 [ $D = 0 ] && : $(($1$2=1)) 
}
 h() {
for (( I=q; I>=0; I--)) {
for (( J=n; J<=o; J++)) {
   [ `g $J $I` = 1 ] && q=$I &&  $r
  }
 }
 }
 
 j() { 
 while read -n 1 S >/dev/null 2>&1
do
$e $S > $M
done
}

G=`mktemp`
L=`mktemp`
M=`mktemp`
N=`mktemp`
X=40
n=0
o=7
q=2
T=0
Y=2
Z=2
U=2
W=0
for (( Q=0; Q<24; Q++)) { 
 K[$Q]=1
}

j 0<&0 &
B=$!

until [ "$z" ]
do
 : $((W++)) 
 if [ -f $M ] 
 then
  i=$(<$M)
  rm $M
  case "$i" in
   q) z="Quit" ;;
   j) X=$(($X-3)) ;;
   l) X=$(($X+3)) ;;
   k) [ $T = 0 ] && S=$((X+1)) && T=22 
   ;;
  esac
 fi
 rm $N  
 exec > $N
for (( J=0; J<=q; J++)) { 
  for (( I=n; I<=o; I++)) { 
   [ `g $I $J` = 1 ] && m $((I*6+Y)) $((J*3+Z)) && $e `f 4`/00\\
  }
 }
 m $X 23
 $e `f 2`"/|\\"
 [ $T != 0 ] && u  
 a
 m 0 0
 exec > `tty`
$c
cat $N
sleep .1
[ $((W%2)) = 0 ] && : $((Y+=U)) && if [ $((Y+n*6)) -lt 2 -o $((Y+o*6)) -gt 75 ] 
then 
: $((U=-U))  $((Z+=2))
[ $((Z+q*3)) -le 20 ] || z="You lose!"
fi
done

$c
$e $z
rm $G $L $M $N $F &> /dev/null
kill $B


04 January 2011

SHELL COMMANDS




 

 
 
|
                ˇ

                |
                ˇ

                |
                ˇ

                |
                ˇ

                |
                ˇ


The most common UNIX / Linux commands
with examples (by om8000@gmail.com):


                |
                ˇ

                |
                ˇ

                |
                ˇ

                |
                ˇ

                |
                ˇ

                |
                ˇ

                |
                ˇ

                |
                ˇ










cal _ _ _ _ _ _ _ _ _ _ _ _ _ _ display a calendar
Dispaly calender for a current monthcal
Dispaly calender for a current yearcal 2008
Display calendar dates for the whole yearscal -y
Display julian dates (number of days from 1 to 365)cal -j
Display a calendarcal -1
Display a calendar with one month before and one in the futurecal -3
Display a calendar for a particular month yearcal 9 2008
for detailed options see:man cal



finger _ _ _ _ _ _ _ _ _ _ _ _ _ _ user info lookup program
For detailed options see:man finger
If you have Lnternet access, get latest kernel info: finger @finger.kernel.org



clear _ _ _ _ _ _ _ _ _ _ _ _ _ _ clear the terminal screen
clear screen if possible clear -or- ctrl+r



write _ _ _ _ _ _ _ _ _ _ _ _ _ _ send a message to another user
Write message to user1 write user2
Write message back to user root write root #(This way two way communication is established (simple chat).)



<><> </></>
wall _ _ _ _ _ _ _ _ _ _ _ _ _ _ send a message to all connected users
Send a administrative message to all users: wall "Server will bew rebooted in 5 minutes"
Someone can also redirect message from a file wall < admin.msg



talk _ _ _ _ _ _ _ _ _ _ _ _ _ _ Talk client for one-on-one Internet chatting
For detailed options see: man talk
Potentially dangerous! Requires talk server to be running!
To talk to another user, just try:
talk user2



mesg _ _ _ _ _ _ _ _ _ _ _ _ _ _ control write access to your terminal
For detailed options see: man mesg
Allow other people to send you messages to the console mesg y
Do not allow other users to send you messages using write or wall mesg n



mkdir _ _ _ _ _ _ _ _ _ _ _ _ _ _ create a directory
For detailed options see: man mkdir
Create two directories simultaneously mkdir dir1 dir2
Create directory g1 inside existing directory r1 in the current directory: mkdir r1/d1
Create complete subdirectory structure at once mkdir -p /tmp/d1/d2/d3
Create directory path d1/d2/d3 underneath the current directory and
set permissions on directory diamond to read-only for all users (a=r):
mkdir -p -m "a=r" d1/d2/d3
mkdir -p -m 444 d1/d1/d3
Creating many directories using curly braces expansion mkdir -p /work/junk/{one,two,three,four}



cd _ _ _ _ _ _ _ _ _ _ _ _ _ _ change the working directory
Go to home directory cd
cd ~
Go to previous directory cd -
Go to dir, execute command and return to current dir (cd dir && command)
Change working directory and if successfull, execute listing cd /tmp && ls
Enter to directory '/ home' cd /home
Go back one level cd ..
Go back two levels cd ../..
for detailed options see: man cd



exit _ _ _ _ _ _ _ _ _ _ _ _ _ _ cause normal process termination
For detailed options see: man exit
Exit with a true value: exit 0
Exit with a false value: exit 1
Some error codes: A file to be executed was found, but it was not an executable utility: 126
A utility to be executed was not found: 127
A command was interrupted by a signal: 128



cp _ _ _ _ _ _ _ _ _ _ _ _ _ _ copy files and directories
Create fast backup of a file cp /etc/fstab{,.bak}
Copy a file to another location cp /tmp/f1 /var/tmp/f2
Make an archive copy of entire directory: cp -a /opt /tmp
To create a zero-length file, using cp: cp /dev/null /tmp/file
Copy a directory within the current work directory and preserve attributes cp -a -p /tmp/dir1 .
Backing up a directory preserving ownerships, permissions and
links, to another partition to hard disk, do:
cp -a /dir-to-backup -or- cp -dpR /dir-to-backup
Copy all files of a directory within the current work directory cp dir/* .
for detailed options see: man cp



ln _ _ _ _ _ _ _ _ _ _ _ _ _ _ make hard/soft links between files
For detailed options see: man ln
Creating soft links: ln -s /etc /var/tmp/etc

NOTE:
Soft links are usefull for linking among different partitions.
Hard links will only work on the same partition/filesystem.
Reason for that are inodes which have different i-numbers on
different filesystems, so filename can not point to them.
Create a physical link to file ln file1 lnk1
The following command creates fl1 and fl2 in destination_dir,
which are linked back to the original files fl1 and fl2. If files on destination
already exist, they will be removed.
ln -f fl1 fl2 destination_dir



who _ _ _ _ _ _ _ _ _ _ _ _ _ _ show who is logged in
For detailed options see: man who
Get inf oabout logged in users who
Show who is logged on, and print: time of last system boot, dead
processes, system login processes, active processes spawned by init,
current runlevel, last system clock change
who -a
Get detailed info with times and processes who --all
Give me info only about me who am I -or- who am i -and also see whoami-
Get runlevel and date using who: who -r



<><> </></>
od _ _ _ _ _ _ _ _ _ _ _ _ _ _ dump files in octal and other formats
For detailed options see: man od
Simple octal output od /etc/passwd
Write hexadecimal bytes and the corresponding octal values to the
standard output in blocks of 16 bytes in one line
od -tx1oC /etc/passwd
The following commands write one line each of the types character,
signed decimal integer, and float, in the order given, transforming
100 bytes of data starting from fifteenth byte offset in the file file1:
od -j14 -N100 -tc -tdfF /etc/passwd
Write one line each of the types unsigned integer, named character, and
long double, with the offsets written in hexadecimal and forcing a write
od -v -Ax -tuafL /etc/passwd
Creating random nubers from urandom device od -An -N2 -tu < /dev/urandom



nautilus _ _ _ _ _ _ _ _ _ _ _ _ _ _ Nautilus is a file manager for GNOME.
start file explorer style nautilus --browser
Samba browser -- basically "Network Neighborhood" nautilus smb:///
Font browser. Click on font to see stuff. nautilus fonts:///
Access the top of My Computer nautilus computer:///
Access network shares nautilus network:///
preparation for burning to CD nautilus burn:///
Displays a whole bunch of themes. You can change your theme from here
nautilus themes:///
browse certain directory nautilus file:///etc/



less _ _ _ _ _ _ _ _ _ _ _ _ _ _ A text file browser similar to more
For detailed options see: man less
See start of some file: less /tmp/bigfile
pgUp/pgDn # browse more
q # exit less command
Try less with line numbering less -N /etc/passwd
Switch to vi edit mode using less while scrolling file with less, just press: v



rmdir _ _ _ _ _ _ _ _ _ _ _ _ _ _ remove empty directories
For detailed options see: man rmdir
To remove empty directory with a prompt for verification: rmdir -i directory
To remove as much as possible of a path, of empty directories type: rmdir -p component1/component2/dir
To remove directory including files: rm -r /tmp/subdir1



strings _ _ _ _ _ _ _ _ _ _ _ _ _ _ show printable characters in binary files
For detailed options see: man strings
Remove ^M andall other control chars within the file strings filename.ext > newfile.ext



pwd _ _ _ _ _ _ _ _ _ _ _ _ _ _ return working directory name
Print cuurent working directory example pwd
Print cuurent working directory disregarding symbolic link pwd -P



whoami _ _ _ _ _ _ _ _ _ _ _ _ _ _ print effective userid
For detailed options see: man whoami
Give me my username: whoami



logout _ _ _ _ _ _ _ _ _ _ _ _ _ _ Logout of a login shell
For detailed options see: man logout
Leaving session logout



xlock _ _ _ _ _ _ _ _ _ _ _ _ _ _ Locks the local X display
To lock X session xlock
Lock the screen with a different screensaver xlock -mode forest
show all possible options on xlock xlock --help



vlock _ _ _ _ _ _ _ _ _ _ _ _ _ _ Virtual Console lock program vlock
To lock current console or terminal vlock
To lock all physical consoles vlock -a



ls _ _ _ _ _ _ _ _ _ _ _ _ _ _ list directory contents
Perform long listing and mark executable files with asterisk ls -bCAFl
get ls to do thousands grouping appropriate to locale BLOCK_SIZE=\'1 ls -l
Print colored output ls --color
List files with full detailed creation time ls --full-time -t
Show files, last changed - last ls -lahtr
List files by date. ls -lrt
Show size of the files and directories ordered by size ls -lSr |more
List files and directories and mark them like: add asterisk for executables
and slash for directories:
ls -F
List directories only at the current path: ls -d */
Use -d switch to list all hidden files and directories at the current path: ls -d .*
Show file attributes and ownership ls -la /tmp/file1
Show files with hidden characters in names ls -b /tmp/*
Show files info node numbes ls -la -i /tmp
Show human readable file sizes ls -lah /tmp
Counting files and subdirs in directory ls -l |wc -l
To list files sorted by size: ls -Sl
Revers sort all files by size ls -laSr
Find all files containing ls in their names ls -lR | grep ps
View files of directory ls
View files of directory ls -F
Show details of files and directory ls -l
Show hidden files ls -a
Knowing inode number of files ls -ail
Show files and directory containing numbers ls *[0-9]*
List biggest files in the current directory last ls -lShr
list without owners info ls -lg *
multicolumn output into file ls -C
give me sorted listing ls -Slh /
for detailed options see: man ls



mv _ _ _ _ _ _ _ _ _ _ _ _ _ _ move (rename) files
For detailed options see: man mv
Rename a file in the current directory: mv old-filename new-filename
Rename a directory in the current directory: mv old-dirname new-dirname
Rename a file in the current directory whose name starts with a nonprinting
control character or a character that is special to the shell, such as -
and * (extra care may be required depending on the situation):
mv ./bad-filename new-filename
mv ./?bad-filename new-filename
mv ./*bad-filename new-filename
Move directory sourcedir and its contents to a new location (targetdir) in
the file system (upon completion, a subdirectory named sourcedir resides
in directory targetdir):
mv sourcedir targetdir
Move all files and directories (including links) in the current
directory to a new location underneath targetdir:
mv * targetdir
Move all files and directories (including links) in sourcedir to a new
location underneath targetdir (sourcedir and targetdir are in separate
directory paths):
mv sourcedir/* targetdir
results with the original files a and b residing
in the directory d in the current directory.
mv a b c
mv c d



more _ _ _ _ _ _ _ _ _ _ _ _ _ _ file perusal filter for crt viewing
For detailed options see: man more
Display file contents page by page more /tmp/bigfile
Display contents of all files in the current directory: more *
Switch to vi edit mode using more
while scrolling file contents using more, just press:
v
To preview nroff output, use a command resembling: nroff -mm +2 doc.n | more -s
If the file contains tables, use: tbl file | nroff -mm | col | more -s
To display file stuff in a fifteen line-window and convert multiple
adjacent blank lines into a single blank line:
more -s -n 15 stuff
To examine each file with its last screenful: more -p G file1 file2
To examine each file starting with line 100 in the current position
(third line, so line 98 is the first line written):
more -p 100g file1 file2
To examine the file that contains the tagstring tag with line 30 in the current position: more -t tag -p 30g
The -p allows arbitrary commands to be executed at the start of each file. more -p G file1 file2
Examine each file starting with its last screenful. more -p 100 file1 file2
Examine each file starting with line 100 in the current position
(usually the third line, so line 98 would be the first line written).
more -p /100 file1 file2



<><> </></> <><> </></> <><> </></> <><> </></> <><> </></> <><> </></> <><> </></> <><> </></> <><> </></> <><> </></> <><> </></> <><> </></> <><> </></> <><> </></> <><> </></>
cat _ _ _ _ _ _ _ _ _ _ _ _ _ _ concatenate and print files
catenate is an obscure word meaning "to connect in a series"
Number row of a file cat -n file1
Join splitted files into one single binary or txt cat xaa xab xac >prog.bin -or- cat x* >prog.bin
To create a zero-length file, using cat: cat /dev/null > file
Get all contetnts from a file cat /tmp/file1
Display a file at ch1
Combine files cat ch1 ch2 ch3 > all
Append to a file cat note5 >> notes
Create file at terminal. To exit, enter EOF (Ctrl-D). cat > temp1
Create file at terminal. To exit, enter STOP. cat > temp2 << STOP
The following prints ^I for all the occurrences of tab character in file1 cat -t file1
To suppress error messages about files that do not exist, use: cat -s file1 file2 file3 > file
To view non-printable characters in file2, use: cat -v file2
general syntax to manipulate a text of a file, and write result to a new file cat file1 | command( sed, grep, awk, grep, etc...) > result.txt
see all characters in a file (also strange ones and from dos ...) cat -vet textfile
join contetnt from files with command output
Command below will show contetnts of header_file first, then result of w
command and after that contetnts of footer_file
w|cat header_file - footer_file
for detailed options see: man cat



rm _ _ _ _ _ _ _ _ _ _ _ _ _ _ remove files or directories
For detailed options see:man rm
Create a safe remove command:

On your system you should put this one into /etc/profile to make it

available for all users. See also function command.



Good think: Instead of removing files and dirs for real, you will save

them into .Trash directory. This function should also prevent all

features of rm -rf to stop a real damage. To rum a real rm command, you

will need to use a full path otherwise you will never remove files for real.
function rm {

mkdir ~/.Trash 2>/dev/null

mv $@ ~/.Trash 2>/dev/null

}
Remove files with a prompt for verification:rm -i file1 file2
Remove all the files in a directory:rm -i mydirectory/*
Remove a file in the current directory whose name starts with - or * or

some other character that is special to the shell:
rm ./-filename

rm \*filename
Remove a file in the current directory whose name starts with some

strange (usually nonprinting, invisible) character:
rm -i *filename*
A powerful and dangerous command to remove a nonempty directory is:rm -rf dir_name
WARNING, DANGEROUS - FOR TESTING PURPOSES ONLY!!!

Remove a whole system while it is running!
# /bin/rm -rf /*
Delete file called 'file1'rm -f file1
Delete directory called 'dir1'rmdir dir1
Remove a directory called 'dir1' and contents recursivelyrm -rf dir1
Remove two directories and their contents recursivelyrm -rf dir1 dir2
Destroy a whole linux server, all settings and programs (DANGEROUS):#rm -rf /*



info _ _ _ _ _ _ _ _ _ _ _ _ _ _ A stand-alone TTY-based reader for GNU texinfo
For detailed options see:man info
For detailed options see:man pinfo
show top-level dir menuinfo
For detailed options see:man info
info emacsstart at emacs node from top-level dir
info emacs buffersstart at buffers node within emacs manual
start at node with emacs' command line optionsinfo --show-options emacs
show file ./foo.info, not searching dirinfo -f ./foo.info



top _ _ _ _ _ _ _ _ _ _ _ _ _ _ display top CPU processes
For detailed options see:man top
For better tool also try:htop
top is text mode process table explorerwill show: cpu, memory, swap utilization, load avg and uptime

will not show: cpu info, system info, platform type ...
Show processes status every second and operate top interactivellytop

sort processes by memory

M

sort processes by CPU

P

show all CPUs

1

exit top

q
show processess status every two seconds and run only three timestop -d2 -n3
create output that is suitable for saving into a filetop -d10 -n100 >/tmp/top.txt
Monitor process identifier (PID) 2233 and 4455, you type:top -p 2233,4455
Monitor processes by root user onlytop -u root
Monitor processes by UID 0 only:top -U 0



fg _ _ _ _ _ _ _ _ _ _ _ _ _ _ run jobs in the foreground
For detailed options see: man fg
Call a job that is suspended or is running in background to the foreground ls -lahR / &
jobs
fg %1



bg _ _ _ _ _ _ _ _ _ _ _ _ _ _ run jobs in the background
To push a running process to the background
freeze it first: ctrl+z
this will produce %1 job identifier
bg %1
for detailed options see: man bg



gnome-system-monitor _ _ _ _ _ _ _ _ _ _ _ _ _ _ Simple process monitor
task manager for gnome, supports process management, load overviev,
disk usage status
gnome-system-monitor
top like graphical application. To start it and manipulate processes: gnome-system-monitor
(use mouse right click to access possible options on processes)
little bug if gnome-system-monitor does not start: killall -9 dbus-daemon dbus-launch
gnome-system-monitor


pstree _ _ _ _ _ _ _ _ _ _ _ _ _ _ display a tree of processes
For detailed options see:man pstree
Show process tree structurepstree
on other unix-esptree
show as much as possible infospstree -aAclpuZ
show tree with processes numberspstree -p





chmod _ _ _ _ _ _ _ _ _ _ _ _ _ _ change file access permissions
There are three permissions for files and directories.

Set permissions:
reading (r)

write (w)

execute (x)

for:

users (u)

group (g)

others (o)

chmod ugo+rwx directory1
Remove permits reading (r), write (w) and (x) access to users group

(g) and others (o)
chmod go-rwx directory1
There are aditiona three special parmissions available for files and directories:STICKY 1000

SGID 2000

SUID 4000
A classic way to change permissions for user : read, write, execute

for group : read, execute

for others: read
chmod 754 /tmp/myprog
But what you really performed is:chmod 0754 /tmp/myprog
Access permissions table

Permissions has a slightly different but significant meaning

on files or directories.


     +------+-----------+-------------------+---------------------------------+
     | mode | notation  | file:             | directory                       |
     +------|-----------|-------------------+---------------------------------+
     | 1000 |---------T | save txt attr:    | link permissions: allow user to |
     |      |           |                   | operate on his own files only   |
     +------|-----------|-------------------+---------------------------------+
     | 2000 |------S--- | set Group ID:     | set Group ID: usable for samba. |
     |      |           |                   | file sharing among users.       |
     +------|-----------|-------------------+---------------------------------+
     | 4000 |           | set User ID:      | set User ID:                    |
     |      |---S------ | usable for suid   |                                 |
     |      |           | programs (passwd) |                                 |
     +------|-----------|-------------------+---------------------------------+
     |    1 |   --x     | execute           | browse                          |
     +------|-----------|-------------------+---------------------------------+
     |    2 |   r--     | read.             | list contents                   |
     +------|-----------|-------------------+---------------------------------+
     |    4 |   -w-     | write.            | create file                     |
     +------+-----------+-------------------+---------------------------------+
    
Add execute-by-user permission to file:chmod u+x /tmp/testprog
Either of the following will assign read/write/execute permission by owner

r/x permission by group, and x-only permission by others to file:
chmod 751 /tmp/testprog chmod u=rwx,g=rx,o=x file
Any one of the following will assign r-only permission to file for everyonechmod =r /tmp/testprog

chmod 444 /tmp/testprog

chmod a-wx,a+r /tmp/testprog
The following makes the executable setuid, assigns read/write/execute

permission by owner, and assigns r/x permission by group and others
chmod 4755 /tmp/testprog
Deny write permission to others:chmod o-w file
Make a file executable by everybody:chmod a+x file
Assign read and execute permission to everybody, and set the set-user-ID bit:chmod a=rx,u+s file
Assign read and write permission to the file owner, and read permission to everybody else:chmod u=rw,go=r file
Set SUID bit on a binary file - the user that running that file

gets same privileges as owner
chmod u+s /bin/file1
Disable SUID bit on a binary filechmod u-s /bin/file1
Set SGID bit on a directory - similar to SUID but for directorychmod g+s /home/public
Disable SGID bit on a directorychmod g-s /home/public
Set STIKY bit on a directory - allows files deletion only to legitimate ownerschmod o+t /home/public
Disable STIKY bit on a directorychmod o-t /home/public
for detailed options see:man chmod



date _ _ _ _ _ _ _ _ _ _ _ _ _ _ print or set the system date and time
Show system date and time: date
Show UTC time: date -u
Set date and tim in more human readable way: date -s "Sat Nov 3 18:59:04 2008"
Convert number of seconds since the epoch to a date: date --date '1970-01-01 UTC 1234567890 seconds'
What day does xmas fall on, this year: date --date='20 Oct' +%A
What date is it this thursday: date -d thu
Set system date and time: date 072315302007 # mmddHHMMyyyy
To set the system clock forward by two minutes: date --set='+2 minutes'
What time is it on West coast of US (use tzselect to find TZ): TZ=':America/Los_Angeles' date
Print custom formatted date: date +%m-%d-%Y
To print the date of the day before yesterday: date --date='2 days ago'
To print the date of the day three months and one day hence: date --date='3 months 1 day'
To print the day of year of Christmas in the current year: date --date='25 Dec' +%j
Display date of the current or next Wednesday: date -d Wed
Give me file creation date:. date -r /tmp/file1
Show yesterday's date: echo $(date +%Y-%m-%d -d '-1 day')
for detailed options see: man date
To print a date without the leading zero for one-digit
days of the month, you can use the (GNU extension)
`-' flag to suppress the padding altogether:
date -d 1may '+%B %-d
To print the current date and time in the format required
by many non-GNU ver.s of `date' when setting the system clock:
date +%m%d%H%M%Y.%S



echo _ _ _ _ _ _ _ _ _ _ _ _ _ _ display a line of text
For detailed options see: man echo
To clear console of gibberish (eg. after cat of a tar.gz file)
go to another virtual console and type in:
echo -e '\017' > /dev/tty1
Print many variable fields in a single line: listing=$(ls -la /)
echo $listing
Print values from variable "as is" listing=$(ls -la /);echo "$listing"
Base conver. (hex to dec) ((shell arithmetic expansion)) echo $((0x2dec))
Base math calcualtions echo $((10+20))
Create an empty file using echo echo > /tmp/new_file1
Print a short beep echo -e "\a"
Start printing on position "two tabs" from start of the line echo -en "\t \t"
Make cursor invisible echo -en "\033[?25l"
Make cursor visible again echo -en "\033[?12l\033[?25h"
Switch terminal to DRAW mode echo -en "\033(0"
Switch terminal back to WRITE mode echo -en "\033(B"
Mark text echo -en "\033[7m"
Unmark text echo -en "\033[27m"
Reset screen echo -en "\033c"
Simple counter with suppressing newlines for NUM in $(seq 1 100)
do
echo -e "\r $NUM \c"
usleep 100000
done
Painting text echo -e "\033[44;37;5m ME \033[0m COOL"
Clear screen but preserver prompt position echo -e "\033[2J"
Clear all keyboard LEDs echo -e "\033[0q"
Set "Scroll Lock" LED echo -e "\033[1q"
Set "Num Lock" LED echo -e "\033[2q"
Set Caps Lock LED echo -e "\033[3q"
beep echo -en "\x07"
Colors

0 reset all attributes to their defaults

1 set bold

2 set half-bright (simulated with color on a color display)

4 set underscore (simulated with color on a color display)

5 set blink

7 set reverse video

22 set normal intensity

24 underline off

25 blink off

27 reverse video off

30 set black foreground

31 set red foreground

32 set green foreground

33 set brown foreground

34 set blue foreground

35 set magenta foreground

36 set cyan foreground

37 set white foreground

38 set underscore on, set default foreground color

39 set underscore off, set default foreground color

40 set black background

41 set red background

42 set green background

43 set brown background

44 set blue background

45 set magenta background

46 set cyan background

47 set white background

49 set default background color


kill _ _ _ _ _ _ _ _ _ _ _ _ _ _ signal a process
For detailed options see: man kill
See for all available signals that can be used with kill man 7 signal
Force closure of the process and finish it kill -9 ID_Process
Force a process to reload configuration kill -1 ID_Process
Reload syslog service using kill command kill SIGINT $(cat /var/run/syslogd.pid)

kill -2 syslogd
Simulate killall command (kill all httpd processes) kill $(ps -ef | grep httpd | awk '{print $2}')
Terminate process many different ways kill -s SIGKILL 1234

kill -s KILL 1234

kill -s 9 1234

kill -SIGKILL 1234

kill -KILL 1234

kill -9 1234
Show all possible signals kill -l
IMPORTANT SGNALS TABLE 0 SIGNULL Null Check access to pid

1 SIGHUP Hangup Terminate; can be trapped

2 SIGINT Interrupt Terminate; can be trapped

3 SIGQUIT Quit Terminate with core dump; can be trapped

9 SIGKILL Kill Forced termination; cannot be trapped

15 SIGTERM Terminate Terminate; can be trapped

24 SIGSTOP Stop Pause the process; cannot be trapped

25 SIGTSTP Terminal stop Pause the process; can be trapped

26 SIGCONT Continue Run a stopped process


killall _ _ _ _ _ _ _ _ _ _ _ _ _ _ kill processes by name
For detailed options see: man killall
also see: pkill
Kill all similar processes by name
(if custom sh script runs of of control)
killall -9 bash sh



konqueror _ _ _ _ _ _ _ _ _ _ _ _ _ _ Web browser, file manager, ..
Faster browsing In KDE 3.2, a little-known but useful option has been added to speed up
your web browsing experience. Start the KDE Control Center and choose
System > KDE performance from the sidebar. You can now select to preload
Konqueror instances. Effectively, this means that Konqueror is run on
startup, but kept hidden until you try to use it.
Starting konqueror in kiosk mode: konqueror --profile KIOSK https://localhost:10000
define profile KIOSK:

vi /root/.kde/share/apps/konqueror/profiles/KIOSK



[Main Window Settings]

MenuBar=Disabled

[Main Window Settings Toolbar Speech Toolbar]

Hidden=true

[Main Window Settings Toolbar bookmarkToolBar]

Hidden=true

[Main Window Settings Toolbar extraToolBar]

Hidden=true

[Main Window Settings Toolbar locationToolBar]

Hidden=true

[Main Window Settings Toolbar mainToolBar]

Hidden=true

[Main Window Settings Toolbar mainMenu]

Hidden=true

[Profile]

FullScreen=false

Name=KIOSK

RootItem=Tabs0

Tabs0_Children=ViewT0

Tabs0_activeChildIndex=0

ViewT0_LinkedView=false

ViewT0_LockedLocation=false

ViewT0_PassiveMode=false

ViewT0_ServiceName=khtml

ViewT0_ServiceType=text/html

ViewT0_ToggleView=false

ViewT0_URL=about:blank

XMLUIFile=konqueror-kiosk.rc



man _ _ _ _ _ _ _ _ _ _ _ _ _ _ display system doc
For detailed options see:man man
biggest man pages collections on webhttp://man.cx

http://www.die.net/doc/linux/man/
show man on ls commandman ls
list all available man pages on the systemman -k [aeiou]|sort|uniq
Get manual pages that start with man (similar to whatis)man -f man
To get a plain text ver. of a man page, without backspaces and

underscores, try
man find | col -b > find.txt
How to write man pageshttp://www.cs.hmc.edu/qref/writing_man_pages.html
Get a custom breaked lines from man pages output:unset LANG

(echo ".nr LL 18.i"; zcat '/usr/share/man/man8/yum.8.gz')|

gtbl | nroff -mandoc |col -b
Make man pages immune to local codepage set:

/etc/man.config:
NROFF /usr/bin/groff -Tlatin1 -mandoc

NEQN /usr/bin/geqn -Tlatin1
Where are the GNU Reference Manuals?http://www.gnu.org/manual/manual.html

http://en.tldp.org/

http://www.redhat.com/docs/manuals/enterprise/

http://www.linuxcommand.org/superman_pages.php
If man pages are formatting incorrectly with PuTTY, try editingthe "/etc/man.config" file with the following changes:

NROFF /usr/bin/groff -Tlatin1 -mandoc

NEQN /usr/bin/geqn -Tlatin1
Creating a ManpageAs root you can copy the following to

/usr/local/man/man1/examples.1

which will give you a manpage for examples:

.\" Manpage for examples.

.\" Contact om8000@hotmail.com to correct errors or omissions.

.TH man 1 "examples"

.SH NAME

examples \- man page for examples

.SH SYNOPSIS

examples

.SH DESCRIPTION

collection of linux and open source tips.

.SH OPTIONS

no options.

.SH SEE ALSO

ls(1), ps(8)

.SH BUGS

No known bugs at this time.

.SH AUTHOR

oTo (om8000@hotmail.com )
man pages sections1 user commands, general commands

2 system calls

3 library functions, Subroutines

4 special files

5 file formats

6 games and demos

7 macros and conventions

8 administration and privileged commands

9 kernel interfce

L math library functions

N tcl functions
also see command below for fast simple man page generation:txt2tags
man2ps - requires postscript installedman -t manpage > manpage.ps


mount _ _ _ _ _ _ _ _ _ _ _ _ _ _ connect filesystems
For detailed options see:man mount
Show mounted filesystems on the system (and align output)mount

mount | column -t
Mount the cdrom image at /mnt/dir (read only)mount -o loop cdrom.iso /mnt/dir
Mount a windows sharemount -t smbfs -o fmask=666,guest //windows_box/share /mnt/share
Mount a windows network sharemount -t smbfs -o username=user,password=pass //WinClient/share /mnt/share
Mounting iso image filemount -o loop /tmp/test.iso /mnt
Mounting a /proc filesystem easy way:mount /proc
hard way (if easy one fails):mount -n -t proc proc /proc
Mountan iso image file:mount -o loop -t iso9660 /img.iso /mnt
Make iso image auto mount at boot time:

Put the following into /etc/fstab
/img.iso /mnt iso9660 ro,loop 0 0
Remount readonly filesystem:mount -o remount,rw /
Mount ext2 formatteed floppymount -t ext2 /dev/fd0 /mnt/floppy
Mount a floppy diskmount /dev/fd0 /mnt/floppy
Mount a cdrom / dvdrommount /dev/cdrom /mnt/cdrom
Mount a cdrw / dvdrommount /dev/hdc /mnt/cdrecorder
Mount a cdrw / dvdrommount /dev/hdb /mnt/cdrecorder
Mount a file or iso imagemount -o loop file.iso /mnt/cdrom
Mount a WIN FAT32 file systemmount -t vfat /dev/hda5 /mnt/hda5
Mount a usb pen-drive or flash-drivemount /dev/sda1 /mnt/usbdisk
Mounting old outdated zip drives

If ZIP drive has been recognised by the kernel ... (dmesg)
modprobe ide-floppy

mount /dev/hdaN /mnt/floppy


mkpasswd _ _ _ _ _ _ _ _ _ _ _ _ _ _ generate new random password
For detailed options see: man mkpasswd
Creating random password example: mkpasswd -l 9 -d 2 -C 3



passwd _ _ _ _ _ _ _ _ _ _ _ _ _ _ setting/changing passwords
For detailed options see: man passwd
Show all /etc/passwd users command prompt: ~< tab >< tab >
Change password for the current user: passwd
Lock an account as root user (insert '!!' in password place): passwd -l user1
Change password for another user (as root): passwd user1
Remove user password: passwd -d user1
Lost password: Log in to Single user mode. At the LILO boot prompt type in :
linux 1 init=/bin/sh root=/dev/hdaN mount rw
(where N is the number of your root partition).
Then change the password for root with the command:
passwd



umount _ _ _ _ _ _ _ _ _ _ _ _ _ _ disconnect filesystems
For detailed options see:man umount
Umount mounted filesystemumount /mnt/cdrom
Run umount without writing the file /etc/mtab - useful when

the file is read-only or the hard disk is full
umount -n /mnt/hda2


vi _ _ _ _ _ _ _ _ _ _ _ _ _ _ visual interactive
vi cheat sheet

    vi Cheat Sheet
    :--------------------------------------------------:  :-----------------:
    | COMMAND MODE                                     |  |                 |
    |                                                  |  |                 |
    |  :--------[coomand mode to edit mode]---------:  |  |                 |
    |  |        I          i [] a         A         |--+--+--> EDIT MODE    |
    |  `--------------------------------------------´  |  |    text typing  |
    |                                                  |  |        |        |
    |  cut, copy, paste    join lines  cursor move     |  |        |        |
    |  :---------------:   :----:      :------------:  |  |        |        |
    |  | dd  yy    p   |   | J  |      |     1G     |  |  |     back to     |
    |  `---------------´   `----´      |     k      |  |  |     command     |
    |                                  | ^ h [] l $ |  |  |     mode        |
    |  delete char,word    save+exit   |      j     |  |  |        |        |
    |  :--------------:    :-------:   |      G     |  |  |      [ESC]      |
    |  | x    X    dw |    |  ZZ   |   `------------´  |  |        |        |
    |  `--------------´    `-------´                 <-+--+--------´        |
    |                                   onetime        |  |                 |
    |  ex mode   search, repeat         undo,redo      |  |                 |
    |  :----:    :----------------:     :--------:     |  |                 |
    |  | :  |    |  /    n        |     | u  .   |     |  |                 |
    |  `----´    `----------------´     `--------´     |  |                 |
    |     |                                 ^          |  |                 |
    `-----|---------------------------------|----------´  `-----------------´
          |                                 |
    :-----|---------------------------------|----------:
    | EX MODE                               |          |
    |                                  :----+------:   |
    |  search & replace                |  [esc]    |   |
    |  :-----------------:             |  [enter]  |   |
    |  | :%s /old/new/g  |             `-----------´   |
    |  `-----------------´                             |
    |                                                  |
    |  change settings    save, exit                   |
    |  :-------------:    :-------------------------:  |
    |  | :set ...    |    | :w :w! :q :q! :wq :x    |  |
    |  `-------------´    `-------------------------´  |
    |                                                  |
    `--------------------------------------------------´


wc _ _ _ _ _ _ _ _ _ _ _ _ _ _ print the number of newlines, words, and bytes in files
c1 d1
c1 d1
c1 d1


webmin _ _ _ _ _ _ _ _ _ _ _ _ _ _ A web-based administration interface for Unix systems.
c1 d1
c1 d1
c1 d1


whereis _ _ _ _ _ _ _ _ _ _ _ _ _ _ locate the binary, source, and manual page files for a command
c1 d1
c1 d1
c1 d1


which _ _ _ _ _ _ _ _ _ _ _ _ _ _ shows the full path of (shell) commands
c1 d1
c1 d1
c1 d1


while _ _ _ _ _ _ _ _ _ _ _ _ _ _ Execute script repeatedly as long as a condition is met
c1 d1
c1 d1
c1 d1


X _ _ _ _ _ _ _ _ _ _ _ _ _ _ graphical - GUI server
c1 d1
c1 d1
c1 d1


xmms _ _ _ _ _ _ _ _ _ _ _ _ _ _ an audio player for X
c1 d1
c1 d1
c1 d1


Xorg _ _ _ _ _ _ _ _ _ _ _ _ _ _ X11R6 X server
c1 d1
c1 d1
c1 d1


yast _ _ _ _ _ _ _ _ _ _ _ _ _ _ Yet another Setup Tool control panel for SuSE
c1 d1
c1 d1
c1 d1


zcat _ _ _ _ _ _ _ _ _ _ _ _ _ _ expand and concatenate data
c1 d1
c1 d1
c1 d1



alias _ _ _ _ _ _ _ _ _ _ _ _ _ _ define or display aliases
c1 d1
c1 d1
c1 d1


awk _ _ _ _ _ _ _ _ _ _ _ _ _ _ pattern scanning and processing language
c1 d1
c1 d1
c1 d1



cut _ _ _ _ _ _ _ _ _ _ _ _ _ _ remove sections from each line of files
c1 d1
c1 d1
c1 d1



do _ _ _ _ _ _ _ _ _ _ _ _ _ _ if loop/case construct keyword
c1 d1
c1 d1
c1 d1


done _ _ _ _ _ _ _ _ _ _ _ _ _ _ end of do loop
c1 d1
c1 d1
c1 d1



dhclient _ _ _ _ _ _ _ _ _ _ _ _ _ _ Dynamic Host Configuration Protocol Client
c1 d1
c1 d1
c1 d1



egrep _ _ _ _ _ _ _ _ _ _ _ _ _ _ print lines matching a pattern
c1 d1
c1 d1
c1 d1


else _ _ _ _ _ _ _ _ _ _ _ _ _ _ conditional operator
c1 d1
c1 d1
c1 d1


expand _ _ _ _ _ _ _ _ _ _ _ _ _ _ convert tabs to spaces
c1 d1
c1 d1
c1 d1


export _ _ _ _ _ _ _ _ _ _ _ _ _ _ set the export attribute for variables
c1 d1
c1 d1
c1 d1


expr _ _ _ _ _ _ _ _ _ _ _ _ _ _ evaluate expressions
c1 d1
c1 d1
c1 d1


fgrep _ _ _ _ _ _ _ _ _ _ _ _ _ _ print lines matching a pattern
c1 d1
c1 d1
c1 d1


fi _ _ _ _ _ _ _ _ _ _ _ _ _ _ end of if-loop/condition construct
c1 d1
c1 d1
c1 d1


file _ _ _ _ _ _ _ _ _ _ _ _ _ _ Figure out what is in an archive file
c1 d1
c1 d1
c1 d1


find _ _ _ _ _ _ _ _ _ _ _ _ _ _ search for files in a directory hierarchy
c1 d1
c1 d1
c1 d1


fmt _ _ _ _ _ _ _ _ _ _ _ _ _ _ simple optimal text formatter
c1 d1
c1 d1
c1 d1


for _ _ _ _ _ _ _ _ _ _ _ _ _ _ loop construct
c1 d1
c1 d1
c1 d1


gnome _ _ _ _ _ _ _ _ _ _ _ _ _ _ The Gnome desktop
c1 d1
c1 d1
c1 d1


gnome-control-center _ _ _ _ _ _ _ _ _ _ _ _ _ _ control panel for Gnome
c1 d1
c1 d1
c1 d1


gnome-sound-properties _ _ _ _ _ _ _ _ _ _ _ _ _ _ sound configurator
c1 d1
c1 d1
c1 d1


grep _ _ _ _ _ _ _ _ _ _ _ _ _ _ print lines matching a pattern
c1 d1
c1 d1
c1 d1


gtv _ _ _ _ _ _ _ _ _ _ _ _ _ _ MP3 and video (MPEG-1) player with GTK+ GUI
c1 d1
c1 d1
c1 d1


gunzip _ _ _ _ _ _ _ _ _ _ _ _ _ _ compress or expand files
c1 d1
c1 d1
c1 d1




gzip _ _ _ _ _ _ _ _ _ _ _ _ _ _ compress or expand files
c1 d1
c1 d1
c1 d1


head _ _ _ _ _ _ _ _ _ _ _ _ _ _ output the first part of files
c1 d1
c1 d1
c1 d1


if _ _ _ _ _ _ _ _ _ _ _ _ _ _ use a Perl module if a condition holds
c1 d1
c1 d1
c1 d1


ifconfig _ _ _ _ _ _ _ _ _ _ _ _ _ _ configure a network interface
c1 d1
c1 d1
c1 d1


init _ _ _ _ _ _ _ _ _ _ _ _ _ _ process control initialization
c1 d1
c1 d1
c1 d1


jobs _ _ _ _ _ _ _ _ _ _ _ _ _ _ display status of jobs in the current session
c1 d1
c1 d1
c1 d1


join _ _ _ _ _ _ _ _ _ _ _ _ _ _ join lines of two files on a common field
c1 d1
c1 d1
c1 d1


kcontrol _ _ _ _ _ _ _ _ _ _ _ _ _ _ kde Control center
c1 d1
c1 d1
c1 d1



kde _ _ _ _ _ _ _ _ _ _ _ _ _ _ KDE Desktop environment
c1 d1
c1 d1
c1 d1


kmix _ _ _ _ _ _ _ _ _ _ _ _ _ _ audio mixer for KDE
c1 d1
c1 d1
c1 d1



kpm _ _ _ _ _ _ _ _ _ _ _ _ _ _ Process manager for KDE
c1 d1
c1 d1
c1 d1


let _ _ _ _ _ _ _ _ _ _ _ _ _ _ bash built-in commands, see bash(1)
c1 d1
c1 d1
c1 d1




locate _ _ _ _ _ _ _ _ _ _ _ _ _ _ find files by name
c1 d1
c1 d1
c1 d1



neat _ _ _ _ _ _ _ _ _ _ _ _ _ _ network configurator
c1 d1
c1 d1
c1 d1


neat-tui _ _ _ _ _ _ _ _ _ _ _ _ _ _ tui network configurator
c1 d1
c1 d1
c1 d1


nice _ _ _ _ _ _ _ _ _ _ _ _ _ _ run a program with modified scheduling priority
c1 d1
c1 d1
c1 d1


nl _ _ _ _ _ _ _ _ _ _ _ _ _ _ number lines of files
c1 d1
c1 d1
c1 d1


noatun _ _ _ _ _ _ _ _ _ _ _ _ _ _ music player for KDE
c1 d1
c1 d1
c1 d1



paste _ _ _ _ _ _ _ _ _ _ _ _ _ _ merge lines of files
c1 d1
c1 d1
c1 d1


pr _ _ _ _ _ _ _ _ _ _ _ _ _ _ convert text files for printing
c1 d1
c1 d1
c1 d1


ps _ _ _ _ _ _ _ _ _ _ _ _ _ _ report a snapshot of the current processes
c1 d1
c1 d1
c1 d1


read _ _ _ _ _ _ _ _ _ _ _ _ _ _ read a line from standard input
c1 d1
c1 d1
c1 d1


renice _ _ _ _ _ _ _ _ _ _ _ _ _ _ alter priority of running processes
c1 d1
c1 d1
c1 d1


rpm _ _ _ _ _ _ _ _ _ _ _ _ _ _ a perl only implementaion of a RPM header reader
c1 d1
c1 d1
c1 d1


sed _ _ _ _ _ _ _ _ _ _ _ _ _ _ stream editor for filtering and transforming text
c1 d1
c1 d1
c1 d1


shift _ _ _ _ _ _ _ _ _ _ _ _ _ _ shift positional parameters
c1 d1
c1 d1
c1 d1


sort _ _ _ _ _ _ _ _ _ _ _ _ _ _ Sorting and merging lists
c1 d1
c1 d1
c1 d1


source _ _ _ _ _ _ _ _ _ _ _ _ _ _ Evaluate a file or resource as a Tcl script
c1 d1
c1 d1
c1 d1


startix _ _ _ _ _ _ _ _ _ _ _ _ _ _ starting X server from console
c1 d1
c1 d1
c1 d1


stat _ _ _ _ _ _ _ _ _ _ _ _ _ _ show detailed information on file attributes
c1 d1
c1 d1
c1 d1


switchdesk _ _ _ _ _ _ _ _ _ _ _ _ _ _ GUI and TUI mode interface for choosing desktop environment
c1 d1
c1 d1
c1 d1


system-config-display _ _ _ _ _ _ _ _ _ _ _ _ _ _ GUI configuring the X Window System display
c1 d1
c1 d1
c1 d1


system-config-network _ _ _ _ _ _ _ _ _ _ _ _ _ _ The GUI of the NEtwork Adminstration Tool
c1 d1
c1 d1
c1 d1


system-config-network-tui _ _ _ _ _ _ _ _ _ _ _ _ _ _ The NEtwork Adminstration Tool
c1 d1
c1 d1
c1 d1


system-config-printer _ _ _ _ _ _ _ _ _ _ _ _ _ _ A printer administration tool
c1 d1
c1 d1
c1 d1


system-config-soundcard _ _ _ _ _ _ _ _ _ _ _ _ _ _ GUI for detecting and configuring soundcards
c1 d1
c1 d1
c1 d1


tac _ _ _ _ _ _ _ _ _ _ _ _ _ _ concatenate and print files in reverse
c1 d1
c1 d1
c1 d1


tail _ _ _ _ _ _ _ _ _ _ _ _ _ _ output the last part of files
c1 d1
c1 d1
c1 d1


tar _ _ _ _ _ _ _ _ _ _ _ _ _ _ The GNU version of the tar archiving utility
c1 d1
c1 d1
c1 d1


tee _ _ _ _ _ _ _ _ _ _ _ _ _ _ read from standard input and write to standard output and files
c1 d1
c1 d1
c1 d1


telinit _ _ _ _ _ _ _ _ _ _ _ _ _ _ process control initialization
c1 d1
c1 d1
c1 d1


test _ _ _ _ _ _ _ _ _ _ _ _ _ _ provides a simple framework for writing test scripts
c1 d1
c1 d1
c1 d1


then _ _ _ _ _ _ _ _ _ _ _ _ _ _ conditional if loop construct
c1 d1
c1 d1
c1 d1


tr _ _ _ _ _ _ _ _ _ _ _ _ _ _ translate or delete characters
c1 d1
c1 d1
c1 d1


true _ _ _ _ _ _ _ _ _ _ _ _ _ _ do nothing, successfully
c1 d1
c1 d1
c1 d1


type _ _ _ _ _ _ _ _ _ _ _ _ _ _ write a description of command type
c1 d1
c1 d1
c1 d1


unexpand _ _ _ _ _ _ _ _ _ _ _ _ _ _ convert spaces to tabs
c1 d1
c1 d1
c1 d1


updatedb _ _ _ _ _ _ _ _ _ _ _ _ _ _ update database for whatis command
c1 d1
c1 d1
c1 d1

03 January 2011

The power of echo command: Bash console drawing methods and some usefull tput-like functions








Have you ever try to write some fancy output that will knock off your co-workers?
Yes you will say, no problem, but have you used Bash to do that?
Have you ever tried to do some menus and graphics under bash?
Yes you will say again, 'dialog' is the right choice for such a task.
But I am very stubborn and I want pure Bash, no external programs, but still some menus and graphics,
and if possible no external programs at all.
And I want at least so much capabilities to be able to build a simple boxes with some colored text.
Is it possible?
Well if you tried to do you homework, you definitely came to some
death end, because bash manual page is not very explanatory on that issue.
But I want to have some old-style text-mode graphics, menus and perhaps message boxes.
And I want to be able to put text where-ever I want on my console.
You would be surprised if I tell you, that most of that can be done with a simple 'echo'
command which is also Bash-builtin.
How I did it
A few years ago my boss tried to convince me that curses library is the only
possible option to produce something fancy on my terminal. But once I opened RedHat's
/etc/init.d/functions file and extracted option for positioning characters at
the current line but at the custom column. I thought - if this is possible, what
else can be done with this nice echo command?
My next step was to run RedHat Setup program and redirect it to an ordinary text file.
That one took me some time. What I've got was a bunch of unreadable characters
that should be responsible for drawing something to the screen. But how? I was confused
for many months. No documentation available or I just did not know how to search for it.
Then I played around with different options the way I deleted part by part of 'garbage' file
produced with some tui aplication outputs and I found out how to switch between
writing and drawing mode at the command line. That one was a real break on my
path of creating some simple pure Bash menu lines.
At the end I redirected some ncurses programs to an empty file and observed what happened.
I ofcource tried many other combinations that work on some terminals, but below is
my result, that should work on most terminal emulators used today.
So, yes you will also need terminal emulator, that supports codes below.
I tested all that stuff on putty and at the Linux console.
Step by step
Right here before you are some not very self-explanatory,
small and usefull functions.
But do not worry, I will explain everything to you.
I will also show you step by step, how you can make those
functions usefull for fancy bash programming.
The Power of echo command
We will start with a simple echo.
Echo can be as powerfull as you can't even imagine.
Just use it with an 'escape' character and extended
option and it will print for you allmost anything.
This 'echo' commad is also bash internal, builtin.
So things just could not get any better.

Creating Custom ESCAPE character
It is mentioned in many manual pages but I did not understood the meaning
of it at he beginning. With the simple words: to make
some characters behave special way, you should put an ESC character infront
of them. ESC character is a single character that takes two places. So it
is impossible just to enter it over keyboard. This is known 'echo' feature and
makes echo a very powerfull command.
echo -en "\033"

Creating Custom Function CLEAR
For start we need a clean screen to work on.
Replacement for 'tput clear' can be simply performed
just by executing 'clear' command.
But I want to be sure just to use bash internals.
So I created a simple echo command, that produces screen erasing.
Escape character in combination with 'c' character will do the work for us.
echo -en "\033c"
Creating Custom Function CIVIS
To create programs with a more realistic look, sometimes it
is nice to hide cursor character.
Replacement for 'tput civis' is reverse engineered.
I typed tput civis and redirected an output to an ordinary text file.
Then I looked inside using vi editor. And here it is.
It will hide your cursor just as good as a real 'tput civis'.
echo -en "\033[?25l"
Creating Custom Function CNORM
Replacement for 'tput cnorm' was created with the same method as command above.
Its function is to make cursor visiible again.
echo -en "\033[?12l\033[?25h"
Creating Custom Function TPUT
Replacement for 'tput cup' should put your cursor anywhere on your terminal.
This can be also easily performed using syntax: echo -en "\033[10:10H".
But since I want to be able to specify my own x and y coordinates I am using
positional parameters ${1} and ${2} which will save my custom console input
and transform it into something usefull.
echo -en "\033[${1};${2}H"
Custom Function COLPUT
RedHat function for column put. This one was hacked from RedHat functions file.
Function is responsible for start writing at the exact position on the current
line without calculating in which line is cursor currently positioned. RedHat
is using it to display services statuses at startup process.
echo -en "\033[${1}G"
Custom Function MARK
Replacement for 'tput smso' should reverse background color around typed text.
I found it the way I simply tested all numbers from 0 to 50. Some were very
interesting but this was the only one more or less working on most terminal
emulators.
echo -en "\033[7m"
Custom Function UNMARK
Replacement for 'tput rmso' that returns selected text back to
normal is created as easily as previous function.
All you need to change is background color back to default (27m).
The code below will do the trick:
echo -en "\033[27m"
Custom Function DRAW
This one along with function DRAW I discovered trying out a bunch of code, that RedHat's
'setup' creates when output is redirected into a file.
When I was seeking for a decend background coloring piece, some garbage came to my screen.
I did not realise at first what this is good for and I thougt it is some console bug.
But after short test it became clear to me that this garbage is actually simple line
drawing and will be very usefull. To be sure to work also on other linux distributions with
some different terminal settings, some RedHat's black magic '%@' is needed. This
will load default console font with special characters that you will need to draw
lines. If not done so, small case characters could be interpreted wrongly. So now we need
to combine 'font switching' and 'draw' mode as two separated commands. I tried to combine
them into one, and so can you, but sometimes the result is not satisfactory.
echo -en "\033%@";echo -en "\033(0"
Custom Function WRITE
When I found 'drawing' mode I also wanted a simple 'return to writing' mode.
Painfull testing method followed.
I tried all letters and numbers and I succeeded!
A very short code below will switch from so called 'garbaged' console back to normal.
echo -en "\033(B"
Custom Function BLUE
To be short I just named it blue.
But it can be easily turned into some other background color.
Search for string 44m and replace it with some of strings listed below.
Result should be impressive.
If not, your terminal does not support this kind of coloring.
What I did is actually very simple.
I reset screen (\033c), I set white color for font and
blue for background ([37;44m) and at the end
I want to apply all of this to the whole screen not only
to my current row ([J).
Select the following codes: 40m for black, 41m for red,
42m for dark green, 43m for light green, 44m for blue,
45m for pink, 46m for green and 47m for gray.
echo -en "\033c\033[1;44m\033[J"

Putting it all together
Here is an example of how to create a true bash functions.
To be always ready, put those function (or the ones you need)
to the start of your every bash script.
This way you will fasten your fancy Bash coding.
ESC(){ echo -en "\033";}                            # escape character
 CLEAR(){ echo -en "\033c";}                           # the same as 'tput clear'
 CIVIS(){ echo -en "\033[?25l";}                       # the same as 'tput civis'
 CNORM(){ echo -en "\033[?12l\033[?25h";}              # the same as 'tput cnorm'
  TPUT(){ echo -en "\033[${1};${2}H";}                 # the same as 'tput cup'
COLPUT(){ echo -en "\033[${1}G";}                      # put text in the same line as the specified column
  MARK(){ echo -en "\033[7m";}                         # the same as 'tput smso'
UNMARK(){ echo -en "\033[27m";}                        # the same as 'tput rmso'
  DRAW(){ echo -en "\033%@";echo -en "\033(0";}        # switch to 'garbage' mode
 WRITE(){ echo -en "\033(B";}                          # return to normal mode from 'garbage' on the screen
  BLUE(){ echo -en "\033c\033[0;1m\033[37;44m\033[J";} # reset screen, set background to blue and font to white
Some real life examples using functions above
Now you have all those functions but you still do not know
how to use them? Let me start with some nice examples and
show you some nice tricks.
Box with a simple progress indicator






 EXECUTING IN PROGRESS:     /    






  

Example shown above can be used in any program that will
take some time to execute.
Code will perform the following tasks:
  1. clear screen (optional)
  2. paint screen (optional)
  3. hide cursor
  4. enable drawing mode
  5. draw fancy box
  6. put text into box
  7. put progress indicator into box
  8. create mechanizm to be able to stop execution
  9. make some space for real program execution
  10. enable writing mode again
  11. put rotating sign always at the same place on the screen
  12. stop screen activity and return the cursor back to visible mode




If you start your code from putty, you should get result similar to the one above.
You will be able to observe rotating cursor for about five seconds. As you can see
there is not too much of code needed (only 42 lines). Give special attention to the
line with a 'trap' command. This one is needed to prevent our script getting
out of control. When you press ctrl+c or some other interrupt combination, 'trap'
will also delete controlling file '/tmp/.waiting' and force subscript to stop.

As you can see a lot of 'q' and some other characters are used. Those characters
will draw some lines inside "drawing" mode for you. To see other characters, switch
to drawing mode and try them out:


Only small case characters will draw something for you.
But if you press large case character it will just present itself as a normal character.
Since screen that looks like a garbage can cause a little panic with you. To be sure, that
you have everything under control, just type 'reset' and it will normalize screen for you again.




Characters shown above should be supported by most terminal emulators. But on some terminals
you will also be able to to get more "drawing" characters to your screen. This way you will also
make your program more terminal dependable. So just try to stick with characters shown above.

Next two articles:
Some fancy and usefull screensavers for system administrators.

Creating fancy pure Bash selection tui-mode menu methods.




echo -en "\033%@";echo -en "\033(0"

Q ─   W ┬   T ├   Z ≥ 

U ┤   A ▒   F °   G ±

J ┘   K ┐   L ┌   Y ≤

X │   V ┴   N ┼   M └

#!/bin/bash
 CLEAR(){ echo -en "\033c";}                            # Predefined functions
 CIVIS(){ echo -en "\033[?25l";}                        # (see description above)
 CNORM(){ echo -en "\033[?12l\033[?25h";}               #
  TPUT(){ echo -en "\033[${1};${2}H";}                  #
  DRAW(){ echo -en "\033%@";echo -en "\033(0";}         #
 WRITE(){ echo -en "\033(B";}                           #
  BLUE(){ echo -en "\033c\033[0;1m\033[37;44m\033[J";}  #

   touch /tmp/.waiting                                  # create an empty control file
   trap "rm -rf /tmp/.waiting;exit 2" 1 2 3 15          # catch interrupt keys (like ctrl+c)

   P1(){ echo -n  '|';}                                 # function P1 (for progress)
   P2(){ echo -n  '/';}                                 #          P2
   P3(){ echo -n '-';}                                  #          P3
   P4(){ echo  -n '\';}                                 #          P4

   CLEAR                                                # clear screen
   BLUE                                                 # make background blue and font white
   CIVIS                                                # hide cursor

   echo -e ""                                           # empty line
   echo -e ""                                           # empty line again

   DRAW                                                 # switch to drawing mode
   echo -e "  lqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqk"         # draw box lines
   echo -e "  x                              x"         #
   echo -e "  x EXECUTING IN PROGRES:        x"         # use large case, since small ones
   echo -e "  x                              x"         # are now used used for drawings
   echo -e "  mqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqj"         #
   WRITE                                                # switch back to normal text input mode

   i=0                                                  # set variable 'i'
   while [ -f /tmp/.waiting ]                           # while file exist
   do                                                   # 
    i=$((++$i))                                         # increase variable i by one each time
     TPUT 5 30 ;P$i                                     # put one of P1, P2, P3 or P4 to exact position

     if [ "$i" = "4" ]; then                            # make sure that variable 'i' will never
        unset i                                         # increase over 4
     fi                                                 #

    usleep 100000                                       # 0.1 second sleep (microsleep)
   done &                                               # fork a subprocess and execute it in background

   # some operation here                                # customize for your needs (put some custom commands)

   sleep 5                                              # sleep for another 5 seconds
   rm -rf /tmp/.waiting                                 # remove control file and stop execution

   TPUT 10 10                                           # put cursor out of the box to another place
   echo ""                                              # make an empty line
   CNORM                                                # Normalize cursor view