Mostrando entradas con la etiqueta Curiosidades. Mostrar todas las entradas
Mostrando entradas con la etiqueta Curiosidades. Mostrar todas las entradas

Audifonos.sh

d
Autor: rain
Descripción: Script para quitar el volumen cuando se desconectan los audífonos
Más información del script en: Desde Linux
NOTA: El script hace uso de alsa-utils por lo que debe instalarse
#!/bin/bash
cd ~
#si no existe el archivo se "instala" en realidad solo copia un archivo
if [ ! -f ".audifonos/con" ]; then
mkdir .audifonos
read -n1 -r -p "Por favor conecte los audifonos y presione una tecla " l
echo;
cp "/proc/asound/card0/codec#0" ".audifonos/con"
echo "si los audifonos estaban desconectados borre la carpeta $HOME/.audifonos y repita"
read -n1 -r -p "instalado - ejecute de nuevo para iniciar" k
echo;
else
encontrado="1"
while true; do
echo $encontrado
 #diff muestra las diferencias entre el archivo codec#0 de alsa y el que copiamos con los audifonos puestos y luego filtramos la info sobre la conexion de audifonos con grep
 diff "/proc/asound/card0/codec#0" ".audifonos/con" | grep Pin-ctls 
 #si $? == 0 entonces los audifonos estan desconectados
 if [ "$?" == "0" ]; then
   #la variable encontrado solo es una forma de controlar el flujo del programa asi permito que cuando este desconectado los audifonos se pueda subir el volumen 
   if [ $encontrado == "0" ]; then
   amixer sset 'Master' 0%
   encontrado="1"
   fi
 
 else
  encontrado="0"

 fi
 #espero 0.5 para que no sea pesado el proceso pero si se quisiera que fuera instantanea se puede quitar o pponer menos tiempo
 sleep 0.1
 
done
fi
Leer más...

rage-quit support for bash

d
Nombre: rage-quit support for bash
Autor: Namuol
Visto en: github namuol
Modificado por: SamHocevar
Validaciones y modificaciones para Debian: @Aen3id
La modificación requiere la instalación del paquete "toilet"
#!/bin/bash

KILL=`killall -9 "$2" 2>&1>/dev/null`
ERR=`echo $?`

if [[ "$2" == "" ]]
 then
  echo ; echo -e "Who the fuck do you want me to kill!?...\n"
 else
   if [ $ERR -ne 0  ]
   then 
    echo; echo -e "Da fuck is $2..?\n"
   else
       echo ; echo -e  "Fuck you $2!!!\n" ; echo " (╯°□°)╯︵$(echo "$2"|toilet -f term -F rotate)"; echo
  fi
 fi
Leer más...

Matrix(ish)

d
Nombre: Matrix(ish)
Autor: Brett Terpstra @ttscoff
Contribuciones: Lauri Ranta and Carl
Visto en: Brettterpstra
#!/bin/bash
#
# matrix: matrix-ish display for Bash terminal
# Author: Brett Terpstra 2012 
# Contributors: Lauri Ranta and Carl 
#
# A morning project. Could have been better, but I'm learning when to stop.
 
### Customization:
blue="\033[0;34m"
brightblue="\033[1;34m"
cyan="\033[0;36m"
brightcyan="\033[1;36m"
green="\033[0;32m"
brightgreen="\033[1;32m"
red="\033[0;31m"
brightred="\033[1;31m"
white="\033[1;37m"
black="\033[0;30m"
grey="\033[0;37m"
darkgrey="\033[1;30m"
# Choose the colors that will be used from the above list
# space-separated list
# e.g. `colors=($green $brightgreen $darkgrey $white)`
colors=($green $brightgreen)
### End customization
 
### Do not edit below this line
spacing=${1:-100} # the likelihood of a character being left in place
scroll=${2:-0} # 0 for static, positive integer determines scroll speed
screenlines=$(expr `tput lines` - 1 + $scroll)
screencols=$(expr `tput cols` / 2 - 1)
 
# chars=(a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 ^)
# charset via Carl:
chars=(ア イ ウ エ オ カ キ ク ケ コ サ シ ス セ ソ タ チ ツ テ ト ナ ニ ヌ ネ ノ ハ ヒ フ ヘ ホ マ ミ ム メ モ ヤ ユ ヨ ラ リ ル レ ロ ワ ン)
 
count=${#chars[@]}
colorcount=${#colors[@]}
 
trap "tput sgr0; clear; exit" SIGTERM SIGINT
 
if [[ $1 =~ '-h' ]]; then
 echo "Display a Matrix(ish) screen in the terminal"
 echo "Usage:  matrix [SPACING [SCROLL]]"
 echo "Example: matrix 100 0"
 exit 0
fi
 
 
clear
tput cup 0 0
while :
 do for i in $(eval echo {1..$screenlines})
  do for i in $(eval echo {1..$screencols})
   do rand=$(($RANDOM%$spacing))
    case $rand in
     0)
      printf "${colors[$RANDOM%$colorcount]}${chars[$RANDOM%$count]} "
      ;;
     1)
      printf "  "
      ;;
     *)
      printf "\033[2C"
      ;;
    esac
   done
   printf "\n"
 
   # sleep .005
  done
  tput cup 0 0
 done
Leer más...

ansiweather

d
Nombre: ansiweather
Autor: Frederic Cambus
Más información del script en fcambus
#!/usr/bin/env bash

###############################################################################
#                                                                             #
# AnsiWeather 1.00 (c) by Frederic Cambus 2013                                #
# https://github.com/fcambus/ansiweather                                      #
#                                                                             #
# Created: 2013/08/29                                                         #
# Last Updated: 2013/10/19                                                    #
#                                                                             #
# AnsiWeather is released under the BSD 3-Clause license.                     #
# See LICENSE file for details.                                               #
#                                                                             #
###############################################################################



###[ Configuration options ]###################################################

config_file=~/.ansiweatherrc

function get_config {
        ret=""
        if [ -f $config_file ]
        then
                ret=$(grep $1 $config_file | awk -F\: '{print $2}')
        fi

        if [ "X$ret" = "X" ]
        then
                return 1
        else
                echo $ret
        fi
}

# Location : example "Moscow,RU"
if [ ! -z "$1" ]
then
        location=$1;
else
        location=$(get_config "location" || echo "Moscow,RU")
fi

# System of Units : "metric" or "imperial"
if [ ! -z "$2" ]
then
        units=$2
else
        units=$(get_config "units" || echo "metric")
fi

# Display symbols : "true" or "false" (requires an Unicode capable display)
symbols=$(get_config "symbols" || echo true)


#### [ Colors and characters ]#################################################

background=$(get_config "background" || echo "\033[44m")
text=$(get_config "text" || echo "\033[36;1m")
data=$(get_config "data" || echo "\033[33;1m")
delimiter=$(get_config "delimiter" || echo "\033[35m=>")
dashes=$(get_config "dashes" || echo "\033[34m-")



###[ Unicode Symbols for icons ]###############################################

sun=$(get_config "sun" || echo "\033[33;1m\xe2\x98\x80")
moon=$(get_config "moon" || echo "\033[36m\xe2\x98\xbd")
clouds=$(get_config "clouds" || echo "\033[37;1m\xe2\x98\x81")
rain=$(get_config "rain" || echo "\xe2\x98\x94")
fog=$(get_config "fog" || echo "\xe2\x96\x92")



###[ Fetch Weather data ]######################################################

fetch_cmd=$(get_config "fetch_cmd" || echo "curl -s")

weather=$($fetch_cmd "http://api.openweathermap.org/data/2.5/weather?q=$location\&units=$units")



###[ Process Weather data ]####################################################

city=$(echo $weather | jq -r '.name')
temperature=$(printf '%.0f' $(echo $weather | jq '.main.temp'))
humidity=$(echo $weather | jq '.main.humidity')
pressure=$(echo $weather | jq '.main.pressure')
sky=$(echo $weather | jq -r '.weather[0].main')
sunrise=$(echo $weather | jq '.sys.sunrise')
sunset=$(echo $weather | jq '.sys.sunset')
wind=$(echo $weather | jq '.wind.speed')



###[ Set the period ]##########################################################

now=$(date +%s)

if [ $now -ge $sunset ] || [ $now -le $sunrise ]
then
        period="night"
else
        period="day"
fi



###[ Set the scale ]###########################################################

case $units in
        metric)
                scale="°C"
                speed_unit="m/s"
                pressureUnit="hPa"
                pressure=$(printf '%.0f' $pressure)
                ;;
        imperial)
                scale="°F"
                speed_unit="mph"
                pressureUnit="inHg"
                pressure=$(printf '%.2f' $(echo "$pressure*0.0295" | bc))
                ;;
esac



###[ Set icons ]###############################################################

if [ $symbols = true ]
then
        case $sky in
                Clear)
                        if [ $period = "night" ]
                        then
                                icon="$moon "
                        else
                                icon="$sun  "
                        fi
                        ;;
                Clouds)
                        icon="$clouds  "
                        ;;
                Rain)
                        icon="$rain  "
                        ;;
                Fog)
                        icon="$fog  "
                        ;;
        esac
fi



###[ Display current Weather ]#################################################

echo -e "$background$text Current weather in $city $delimiter$data $temperature $scale $icon$dashes$text Humidity $delimiter$data $humidity % $dashes$text Wind $delimiter$data $wind $speed_unit $dashes$text Pressure $delimiter$data $pressure $pressureUnit \033[0m"

Leer más...

ListaModulos.pl

d
Nombre: ListaModulos.pl
Autor: Desconocido
Visto en: davioth
#!/usr/bin/perl
use strict;
use ExtUtils::Installed;

my $instmod = ExtUtils::Installed->new();

foreach my $module ($instmod->modules()) {
      my $version = $instmod->version($module) || "???";
      print "$module $version\n";
}
Leer más...

WhoPingMe.py

d
Script: WhoPingMe.py
Description: Detect if you receive a Ping and make a list with Date.
Autor: @LordRNA


#! /usr/bin/env python
########################################################################
#Script     : WhoPingMe.py                                             #
#Description: Detect if you receive a Ping and make a list with Date.  #
#By         : LordRNA                                                  #
#Comments   : Tested on Python 2.6.5                                   #
########################################################################
import socket, datetime
def whopingme(date):

    source = '' #To put the IP Source.
    header = ["%i"%ord(x) for x in data]
#I made a list of int values for each byte in data variable. 
    if int(header[20])==8:#If Type(ICMP) is 8, i received a Echo Request.
        for x in range(4):#To make a string with the IP Source.
            source += str(header[12+x])
            if x<3:source data-blogger-escaped----="---" data-blogger-escaped-date="date" data-blogger-escaped-len="len" data-blogger-escaped-print="print"> "+ str(source)
#I deleted the Miliseconds with [:len(date)-7]

sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)

#ICMP Protocol on RAW Socket

while 1:

    data = sock.recv(21)#I Just want these bytes, IPHeader Lenght + Type(ICMPHeader)
    whopingme(data)#Sending data to whopingme() function.
Leer más...

[Python] Goo - Acorta tu URL

d
Autor: @The_Swash
Descripción : Un acortador de url que la obtiene de goo.gl

#----------------------------------------------------------
# Obtener URL acortada mediante http://goo.gl
# Programador: The Swash
# Agradecimientos: Psymera, 11Sep, [Zero] y todo h-sec
# Website: http://h-sec.org
#----------------------------------------------------------
 
import socket, urllib, re
def GetGooURL(url):
    header = ['POST /api/shorten HTTP/1.1\r\n',
              'Host: goo.gl\r\n',
              'Content-Type: application/x-www-form-urlencoded;charset=utf-8\r\n',
              'Content-Length: 41\r\n',
              'Connection: close\r\n\r\n',
              'URLENCODE']
    if re.match('^http://', url):
        url2 = url
    else:
        url2 = 'http://' + url
    address = socket.gethostbyname('goo.gl')
    link = urllib.urlencode({'url':url2})
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    header[5] = link + '&security_token\r\n'
    length = len(header)
    try:
        sock.connect((address,80))
        for i in range(length):
            sock.send(header[i])
        buff = sock.recv(1024)
    except:
        return 'Error de conexion'
     
    sock.close()
    data = re.findall('Location: (.+)\r\n', buff)
    return data[0]
 
url = GetGooURL('h-sec.org')
print url
raw_input()
Leer más...

¿Cuándo se debe enviar un tweet?

d
Nombre: when_to_tweet.sh
Autor:@orvtech
Descripción:
Inicializa archivos temporales a usar y declara cual es el Twitter Handle (nick) de la cuenta a analizar.
Pide un listado de los IDs de todos los seguidores de esa cuenta.
Busca el numero de seguidores que tiene cada uno de tus seguidores.
Ordena tus seguidores en base a la cantidad de seguidores que estos tengan y toma los top doscientos.
Busca en el timeline de cada uno de estos seguidores por fechas y horas de actualización de estados.
Traduce la fecha a formato POSIX o epoch.
Hace un ajuste de horario basado en segundos, como estoy en la costa oeste de Estados Unidos y estamos en daylight savings time, la diferencia son -7 horas, lo que se traduce a -25.200 segundos.
Redondea la hora en base a 20 minutos.
Determina si la actividad fue un día de semana o un fin de semana y registra la hora en el archivo correspondiente.
Analiza los dos archivos y determina que hora se repite mas asignando a cada uno un porcentaje en base a cuantas veces se repiten.
Presenta el resultado en la consola.
Visto en orvtech
#!/bin/bash
# Tenemos un limite de 150 peticiones por hora
echo > /tmp/TweetsOnWeekends.txt
echo > /tmp/TweetsOnWeekdays.txt
echo > /tmp/WhenToTweet.txt
MyHandle="orvtech"
curl -s "http://api.twitter.com/1/followers/ids.xml?screen_name=$MyHandle" | grep -E '\]*>//g;/ /tmp/followers_ids.txt
echo "Got the list of your followers, lets wait a minute before proceeding"
sleep 25
for IDFollowers in `grep -E '[0-9]' /tmp/followers_ids.txt`
do echo $IDFollowers | tr '\n' ','
curl -s "https://api.twitter.com/1/users/lookup.xml?user_id=$IDFollowers&include_entities=true" | \
grep -E '\|followers_count\>' -m 2 | \
sed -e :a -e 's/<[^>]*>//g;/ /tmp/followers_followed.txt
echo "Now I know how many followers they have, I will take a sample of the top 200 of them based on the amount of followers. Lets find out when they are more active."
for follower_timelines in `grep [0-9] /tmp/followers_followed.txt | sort -t \, -k3 -n -r | awk -F\, '{print $1}' | head -n 200`
do sleep 25
curl -s "https://api.twitter.com/1/statuses/user_timeline.xml?include_entities=true&include_rts=true&user_id=$follower_timelines" | \
grep \ | grep `date +%Y`|sort | uniq -c | grep " 1 " | cut -f2- -d '1' | sed -e :a -e 's/<[^>]*>//g;/ /tmp/WhenToTweet.txt
ls -lah /tmp/WhenToTweet.txt
echo "Now, lets separate weekends from weekdays."
cat /tmp/WhenToTweet.txt | while read WhenToTweet
do
if [[ "$WhenToTweet" =~ .*Sat.* ]]
then echo $WhenToTweet >> /tmp/TweetsOnWeekends.txt
else
if [[ "$WhenToTweet" =~ .*Sun.* ]]
then echo $WhenToTweet >> /tmp/TweetsOnWeekends.txt
else
echo $WhenToTweet >> /tmp/TweetsOnWeekdays.txt
fi
fi
done
echo -e "\nDuring the week is best to tweet at:"
cat /tmp/TweetsOnWeekdays.txt | awk '{print $2}' | grep [0-9]0:00 | sort | uniq -c | sort -n -r | awk '{a[NR] = $1; sum+= $1; b[NR]=$2 } END { for (i = 1; i <= NR; i++) printf "\t %2.2f% Activity at %s \n ", (100 * a[i])/sum, b[i] } ' | head -n 10
echo "------------------------------------"
echo
echo "Weekends is best at:"
cat /tmp/TweetsOnWeekends.txt | awk '{print $2}' | grep [0-9]0:00 | sort | uniq -c | sort -n -r | awk '{a[NR] = $1; sum+= $1; b[NR]=$2 } END { for (i = 1; i <= NR; i++) printf "\t %2.2f% Activity at %s \n ", (100 * a[i])/sum, b[i] } ' | head -n 10
echo "------------------------------------"
Leer más...

Ver información básica de una cuenta de Twitter usando BASH

d
Nombre: twitter-creado.sh
Autor: @orvtech
Descripción: Este script muestra cuando fue creada la cuenta además de cuantas personas sigue, cuantos lo siguen y cuantos tweets ha publicado.
Visto en: Orvtech
#!/bin/bash
if [ $# -ne 1 ]; then
 echo "Falta un parámetro"
 echo "Uso $0 handle"
 exit 1
fi
curl -s "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=$1&count=0" | tr ',' '\n' | grep \"created_at\" | tail -n 1
curl -s "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=$1&count=0" | tr ',' '\n' | grep -m2 -E 'friends_count|statuses_count|followers_count'
Permisos: chmod 700 twitter-creado.sh 
Ejecución: ./twitter-creado.sh orvtech
Lo que veremos en la terminal será información sobre el handle:
"created_at":"Thu Apr 12 21:35:06 +0000 2007"
"friends_count":236
"statuses_count":5065
"followers_count":251
Leer más...

URL Shortner

d
Autor: Jorge Pizarro Callejas
Descripcion: Script que permite acortar una URL.
Funcionamiento: ./urlshortener (url para acortar)
#!/bin/sh
#Script programado por Jorge Pizarro Callejas (aka Jorgicio)
#Envíen sus correcciones a [jpizarro@inf.utfsm.cl]

#Donde url es el parámetro, la url que quieres acortar
#Verifiquemos si tienes curl
whereis curl
if [ $? == 1 ];then
    echo "Necesitas curl para que funcione. Instálalo con tu gestor de paquetes favorito."
else
    #Verifiquemos si tienes html2text
    whereis html2text
    if [ $? == 1 ];then
        echo "Necesitas html2text para que funcione. Instálalo con tu gestor de paquetes favorito."
    else
        curl -s -A Mozilla 'http://3.ly/?bm=1&u='$1 | html2text | grep ready
    fi
fi
Leer más...

QuickCheckGmail.bash

d
Nombre: QuickCheckGmail.bash
Autor: Desconocido
Descripción: Script que permite verificar si se tiene nuevo correo en gmail desde la terminal.
Visto en Shell Person
#!/bin/bash
## Quickly checks if I have new gmail
 
echo -e "Checking for new messages... \c"
 
atomlines=`wget -T 3 -t 1 -q --secure-protocol=TLSv1 \
 --no-check-certificate \
 --user=USERNAME --password=PASSWORD \
 https://mail.google.com/mail/feed/atom -O - \
 | wc -l`
 
echo -e "\r\c"
 
[ $atomlines -gt "8" ] \
 && echo -e " You have new gmail.  \c" \
 || echo -e " No new gmail.  \c"
Leer más...

Ruletas Rusas solo para arriesgados

d
Autor: @jorgicio
Descripción: Script para jugar a la ruleta ;)
Nota: No nos hacemos responsable por el uso de los siguientes script, solo los traemos para poder dar a conocer, la ejecución de los mismos es total responsabilidad del que los haga correr.
Verifica si eres root si es asi simplemente reinicia el sistema.

#!/bin/sh
ROOT_UID=0
if [ "$UID" -eq "$ROOT_UID" ]; then
    [ $[ $RANDOM % 6 ] == 0 ] && (echo "Moriste xD" && sleep 3 && /sbin/reboot ) || echo "Tu sistema aun vive"
else
    echo "Para jugar a la ruleta rusa debes ser root"
fi
exit 0

Lo mismo borra el directorio raiz (Root)

#!/bin/sh
ROOT_UID=0
if [ "$UID" -eq "$ROOT_UID" ]; then
    [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo "Tu sistema aun vive"
else
    echo "Para jugar a la ruleta rusa debes ser rooEtiquetast"
fi
exit 0
#!/bin/sh
[ $[ $RANDOM % 6 ] == 0 ] && (echo "moriras muahahahahaha" && :(){ ;|:& };: ) || echo "Todo esta bajo control" 

Ruleta rusa con Fork Bomb pero en Python


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import random
def fork_bomb():
    while True:
        os.fork()
aleatorio = random.randint(0,100000000)
if aleatorio % 6 == 0:
    fork_bomb()
else:
    print "Te salvaste weon xD"
Leer más...

Script para limpiar la memoria de Linux

d
Autor:  Kalambu
Descripción:  Script que nos permite liberar la memoria en Linux.
Visto en: Kalambu

Uso: puede cambiar la variable percent = 70 por la que deseemos para que posteriormente lo libere

#!/bin/sh
PATH=”/bin:/usr/bin:/usr/local/bin”
# Porcentagem maxima (mude se vc achar q deve) eu deixo em 70%
percent=70
 
# Total da memoria:
ramtotal=`grep -F “MemTotal:” < /proc/meminfo | awk ‘{print $2}’`
# Memoria livre:
ramlivre=`grep -F “MemFree:” < /proc/meminfo | awk ‘{print $2}’`
 
# RAM utilizada pelo sistema:
ramusada=`expr $ramtotal – $ramlivre`
 
# Porcentagem de RAM utilizada pelo sistema:
putil=`expr $ramusada \* 100 / $ramtotal`
 
echo =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
date
echo
echo “Mem. utilizada: $putil %”;
 
if [ $putil -gt $percent ]
then
date=`date`
echo $date >> /var/log/memoria.log
echo “Mem. utilizada: $putil %” >> /var/log/memoria.log
 
echo “Memoria acima de $percent %, cache foi limpado!”;
sync
# ‘Dropando’ cache:
echo 3 > /proc/sys/vm/drop_caches
echo
free -m
echo
echo =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
else
echo “Não há necessidade de limpar o cache!”;
echo =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
unset percent ramtotal ramlivre ramusada putil
exit $?
fi
Leer más...

Space Invaders

d
Nombre: Space.bash
Autor: Steve Parker.
Descripción: Script que emula el famoso juego de 1978.
Visto en nixshell
Y el libro Shell Scripting de Steve Parker, Capítulo 17. Página 464.
#!/bin/bash
stty -echo
tput civis
clear
cat - << EOF



           SPACE

   LEFT:      a
   RIGHT:     l
   FIRE:      f

   QUIT:      q

                            Press any key.
EOF
read -s -n 1
row0=( 0 30 30 30 30 30 30 30 30 )
row1=( 0 20 20 20 20 20 20 20 20 )
row2=( 0 15 15 15 15 15 15 15 15 )
row3=( 0 10 10 10 10 10 10 10 10 )
row4=( 0 5 5 5 5 5 5 5 5 )
row5=( 0 1 1 1 1 1 1 1 1 )

aliens1=( '\033[1;32m|0|\033[0m' '\033[1;34m\-/\033[0m'
          '\033[1;35m:x:\033[0m' '\033[1;38m:#:\033[0m'
          '\033[1;33m!|!\033[0m' '\033[1;39m:-:\033[0m' )
aliens2=( '\033[1;32m:0:\033[0m' '\033[1;34m/-\\\033[0m'
          '\033[1;35m-x-\033[0m' '\033[1;38m-#-\033[0m'
          '\033[1;33m:|:\033[0m' '\033[1;39m-:-\033[0m' )

score=0

# farthest right that the *leftmost* alien can go to
MAXRIGHT=46
# furthest right that the ship can go to
FARRIGHT=73

# Ship's current position (x-axis)
ship=30
# Cannon column; remains the same even if ship moves
cannonX=$ship
# Cannon height; 0 means it's ready to fire
cannonY=0
# Positive direction to right, Negative to left
direction=1
offset=20
bottom=20
ceiling=4
MAXCEILING=6
DELAY=0.4

drawrow()
{
  # draw a row of aliens; return the index of any alien killed
  # note that only one alien can be killed at any time.
  alientype=$1
  shift
  let row="$alientype * 2 + $ceiling"
  aliensonrow=`echo $@ | tr ' ' '+' | bc`
  if [ $aliensonrow -eq 0 ]; then
    # Nothing to do here. In particular, do not detect failure.
    # Just clear the previous line (it may contain the final explosion
    # on that row) and return.
    tput cup $row 0
    printf "%80s" " "
    return 0
  fi
  if [ $row -eq $bottom ]; then
    tput cup `expr $bottom - 4` 6
    trap exit ALRM
    clear
    echo "YOU LOSE"
    sleep $DELAY
    stty echo
    tput cnorm
    exit 1
  fi
  declare -a thisrow
  thisrow=( `echo $@` )

  tput cup 0 0
  printf "Score: %-80d" $score

  killed=0
  # Clear the previous line
  tput cup `expr $row - 1` 0
  printf "%80s" " "

  tput cup $row 0
  printf "%80s" " "
  tput cup $row 0
  printf "%-${offset}s"

  # Don't do this calculation in the for loop, it is slow even without expr
  if (( $offset % 2 == 0 )); then
    thisalien=${aliens1[$alientype]}
else
    thisalien=${aliens2[$alientype]}
  fi

  # there are 8 aliens per row.
  for i in `seq 1 8`
  do
    value=${thisrow[$i]}
    avatar=$thisalien
  
    if [ $value -gt 0 ]; then
      # detect and mark a collision
      if [ $row -eq $cannonY ]; then
        let LEFT="$i * 4 + $offset - 4"
        let RIGHT="$i * 4 + $offset - 1"
        if [ $cannonX -ge $LEFT ] && [ $cannonX -le $RIGHT ]; then
          killed=$i
 avatar='\033[1;31m***\033[0m'
          ((score=$score + $value))
          cannonY=0
        fi
      fi
    fi

    if [ $value -eq 0 ]; then
      printf "    " 
    else
        echo -en "${avatar} "
    fi
  done
  return $killed
}

drawcannon()
{
  # move the cannon up one
  if [ $cannonY -eq 0 ]; then
    # fell off the top of the screen
    return
  fi

  tput cup $cannonY $cannonX
  printf " "
  ((cannonY=cannonY-1))
  tput cup $cannonY $cannonX
  echo -en "\033[1;31m*\033[0m"
}

drawship()
{
  tput cup $bottom 0
  printf "%80s" " "
  tput cup $bottom $ship 
  # Show cannon state by its color in the spaceship
  if [ $cannonY -eq 0 ]; then
    col=31
  else
    col=30
  fi
  echo -en "|--\033[1;${col}m*\033[0m--|"
}

move()
{
  # shift aliens left or right
  # move cannon, check for collision
  (sleep $DELAY && kill -ALRM $$) &
  # Change direction if hit the side of the screen
  if [ $offset -gt $MAXRIGHT ] && [ $direction -eq 1 ]; then
    # speed up if hit the right side of the screen
    DELAY=`echo $DELAY \* 0.90 | bc`
    direction=-1
    ((ceiling++))
  elif [ $offset -eq 0 ] && [ $direction -eq -1 ]; then
    direction=1
  fi

  ((offset=offset+direction))
  drawrow 0 ${row0[@]}
  row0[$?]=0
  drawrow 1 ${row1[@]}
  row1[$?]=0
  drawrow 2 ${row2[@]}
  row2[$?]=0
  drawrow 3 ${row3[@]}
  row3[$?]=0
  drawrow 4 ${row4[@]}
  row4[$?]=0
  drawrow 5 ${row5[@]}
  row5[$?]=0

  aliensleft=`echo ${row0[@]} ${row1[@]} ${row2[@]} ${row3[@]}\
         ${row4[@]} ${row5[@]} \
      | tr ' ' '+' | bc`
  if [ $aliensleft -eq 0 ]; then

    tput cup 5 5
    trap exit ALRM
    echo "YOU WIN" 
    sleep $DELAY
    #tput echo 
    tput cnorm
    echo; echo; echo
    exit 0
  fi
  drawcannon
  drawship
}

trap move ALRM
clear
drawship
# Start the aliens moving...

move

while :

do
  read -s -n 1 key
  case "$key" in
    a) 
       [ $ship -gt 0 ] && ((ship=ship-1)) 
 drawship
 ;;
    l)
       [ $ship -lt $FARRIGHT ] && ((ship=ship+1)) 
 drawship
 ;;
    f)
 if [ $cannonY -eq 0 ]; then
          let cannonX="$ship + 3"
   cannonY=$bottom
        fi
 ;;
    q)
 clear
 echo "Goodbye!"
 tput cnorm
 stty echo
 trap exit ALRM
 sleep $DELAY
 exit 0
 ;;
  esac
done
Permisos: chmod 700 space.bash 
Ejecución: ./space.bash
Movimientos del juego LEFT: a
RIGHT: l
FIRE: f
QUIT: q
Leer más...

Tic Tac Toe

d
Nombre:ttt.bash
Autor: Chris F.A. Johnson
Descripción: Script que permite jugar Tic Tac Toe en la terminal contra la máquina.
Visto en cfaj
#!/bin/bash
# Sat Jul 12 16:52:30 EDT 2003
# NAME: ttt
# Copyright 2003, Chris F.A. Johnson
# Released under the terms of the GNU General Public License

ESC=$'\e'

tictactoe() {
[ $verbose -ge 1 ] && echo tictactoe $* >&2
    board=`printf "%9.9s" "        "`
    mvnum=1
    remainder=" 1 2 3 4 5 6 7 8 9 "
    show "$board"
    while :
    do
      status
      eval \$player$P
      [ $? -ne 0 ] && return
      put $_MOVE "$board"
      board=$_PUT
#      show "$board"
      mkbold "$_MOVE"
      printat 0 0 $mvnum
      printat $prompt
      sleep $pause &
      mlist="$mlist $_MOVE"
      remainder=${remainder/ $_MOVE / }

      checkboard "$board" && {
   mkbold $win
   printat $prompt "$cle"
   eval winner \$player$P
   return
      }

      [ $mvnum -eq 9 ] && {
   B=$U mkbold "$_MOVE"
   winner "Neither player"
   return
      }
      wait
      B=$U mkbold "$_MOVE"
      if [ $P = O ]
      then
   P=X
   OP=O
      else
   P=O
          OP=X
      fi
      mvnum=$(( $mvnum + 1 ))
    done
}

winner() {
[ $verbose -ge 1 ] && echo winner $* >&2
     printat $prompt "$cle $* wins\n\n"
}

status() {
[ $verbose -ge 1 ] && echo status $* >&2
    if [ $verbose -ge 1 ]
    then
 printat 4 0
 printf "${cle}Move: %s Player: %s Board: \"%s\"  Last move: %s  Move list: %s" \
     "$mvnum" "$P" "${board// /-}" "$_MOVE" "$mlist"
    else
 false
    fi
}

show() {
[ $verbose -ge 1 ] && echo show $* >&2
    printat 0 0 $mvnum
    printat 0 $top  ##$(( ($LINES - 5) / 2 ))
    printf "  %${margin}.${margin}s | %1s | %1s\n" "${1:0:1}" "${1:1:1}" "${1:2:1}"
    printf "%${margin}.${margin}s---+---+---\n" " "
    printf "  %${margin}.${margin}s | %1s | %1s\n" "${1:3:1}" "${1:4:1}" "${1:5:1}"
    printf "%${margin}.${margin}s---+---+---\n" " "
    printf "  %${margin}.${margin}s | %1s | %1s\n" "${1:6:1}" "${1:7:1}" "${1:8:1}"
}

put() {
[ $verbose -ge 1 ] && echo put $1 \""$2"\" >&2
   local n=$(( $1 - 1 ))
   _PUT=${2:-$board}
   [ "${_PUT:$n:1}" = " " ] &&
            _PUT=${_PUT:0:$n}$P${_PUT:$1}
}

checkboard() {
[ $verbose -ge 1 ] && echo checkboard \"$*\" >&2
    case $1 in
 $P??$P??$P??) win="1 4 7" ;;
 ?$P??$P??$P?) win="2 5 8" ;;
 ??$P??$P??$P) win="3 6 9" ;;
 ??$P?$P?$P??) win="3 5 7" ;;
        $P???$P???$P) win="1 5 9" ;;
 $P$P$P??????) win="1 2 3" ;;
 ???$P$P$P???) win="4 5 6" ;;
 ??????$P$P$P) win="7 8 9" ;;
        *) false ;;
    esac
}

mkbold() {
[ $verbose -ge 1 ] && echo mkbold $* >&2
  for sq in $*
  do
    row=$(( ($sq - 1) / 3 ))
    col=$(( ($sq - 1) % 3 + 1 ))
    printat $(( ($col * 4) + $margin - 2 )) $(( ($row * 2) + $top ))
    printf "${B}$P${U}"
  done
}

human() {
[ $verbose -ge 1 ] && echo human $* >&2
   while :
   do
       key "Select ($remainder)"
#       case $_MOVE in
#   "$ESC") read -sn1; read -sn1 kp; continue ;;
#       esac
       _MOVE=$_KEY
       case $_MOVE in
    1|2|3|4|5|6|7|8|9) [ "${board:_MOVE-1:1}" = " " ] && break ;;
    q|Q|x|X) echo; return 5 ;;
    p) printat $prompt
       KEYECHO= KEYMAX=$(( $COLUMNS - 10 )) key "Enter delay in seconds"
       pause=$_KEY
       ;;
    "") set -- $remainder
        _MOVE=$1
        [ $verbose -ge 1 ] && echo "|$_MOVE|" >&2
        break ;;
    *) printat $prompt
       printf "\r%s%s\r" "  "$cle" $_MOVE: Invalid move"
       sleep 1
       printf "%s\r" "$cle" ;;
       esac
   done
}

randy() {
[ $verbose -ge 1 ] && echo randy $* >&2
    randstr $remainder
    _MOVE=$_RANDSTR
}

key() {
[ $verbose -ge 1 ] && echo key $* >&2
    printat $prompt "$cle$CVIS$beep"
    read -${KEYECHO}n$KEYMAX -p "${1:-PAK}: " _KEY 2>&1
    printf "$CINV"
}

getkey() {
    local OKchars=${1:-${remainder// /}}
    local kp2 kp3
    stty -echo
    while :
      do
      prompt="==>"
      prompt
      IFS= read -r -sn1 -p " " kp 2>&1 || exit 2 #cleanup
      case $OKchars in
          *"$kp"*)
              case $kp in
                  $ESC)
                      read -st1 -n1 kp2
                      case $kp2 in
                          \[) read -st1 -n1 kp3
                              case $kp3 in
                                  A) kp=$UP; break ;;
                                  B) kp=$DN; break ;;
                                  C) kp=$RT; break ;;
                                  D) kp=$LF; break ;;
                              esac
                              ;;
                       esac
                       ;;
                  *) break ;;
              esac
              ;;
       esac
    done
    _KEY=$kp
}

randstr() {
[ $verbose -ge 1 ] && echo randstr $* >&2
#    [ -n "$1" ] || return 1
    n=$(( ($RANDOM % $#) + 1 ))
    eval _RANDSTR=\${$n}
}

isblock() {
[ $verbose -ge 1 ] && echo isblock $* >&2
    win=
    block=
    for _MOVE in $remainder
    do
        P=$OP put $_MOVE
 P=$OP checkboard "$_PUT" && return
    done
    _MOVE=
}

block() {
[ $verbose -ge 1 ] && echo block $* >&2
    block=
    for _MOVE in $remainder
    do
        put $_MOVE
 checkboard "$_PUT" && return
        P=$OP put $_MOVE
 P=$OP checkboard "$_PUT" && block=$_MOVE
    done
    [ "$block" ] && { _MOVE=$block; return; }
    randy
}

computer() {
[ $verbose -ge 1 ] && echo computer $* >&2
   local r c
   case $mvnum in
       1) randstr 1 3 7 9
   _MOVE=$_RANDSTR ;;
       2)
    if [ "${board:4:1}" = " " ]
    then
        _MOVE=5
    else
        randstr 1 3 7 9
        _MOVE=$_RANDSTR
    fi
    ;;
       3)  r=${mlist// /}
    c='1 3 7 9'
    randstr ${c//[$r]/}
#    randstr ${remainder//[$r]/}
    _MOVE=$_RANDSTR
    ;;
       4)
    isblock
    [ "$_MOVE" ] && return
     r=${mlist// /}
     c='2 4 6 8'
     randstr ${remainder//[$r]/}
     _MOVE=$_RANDSTR
     ;;
       *) block ;;
   esac
}

printat() { #== print arguments 3-... at Y=$2 X=$1
[ $verbose -ge 1 ] && echo printat $* >&2
    [ $# -lt 2 ] && return 1
    local y=$2
    local x=$1
    shift 2
    msg="$*"
    printf "\e[%d;%dH%b" $y $x "$msg"
}

version()
{
    echo "    $progname, version $version
    Copyright $copyright, $author $email
    This is free software, released under the terms of the GNU General
    Public License.  There is NO warranty; not even for MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.
"
}

usage()
{
echo "
    ${B}NAME${U}:  $progname - Tic-Tac-Toe

    ${B}USAGE${U}: $progname [OPTIONS]

    ${B}OPTIONS${U}:

        -x player1         - specify first player
        -o player2         - specify second player
        -c player1,player2 - specify both players
        -p seconds         - time to pause between moves

        -h, --help       - help: print this message
        -H, --help_long  - help: print more detailed message (if available)
        -v, --verbose    - sends messsages to \$HOME/tttlog
        -V, --version    - print version information

    Copyright 2003, Chris F.A. Johnson
"
}

verbose=0
longusage=0
version="1.0"
copyright=2003
author="Chris F.A. Johnson"
progname=${0##*/}
P=X
OP=O

playerX=human
playerO=computer
co=
li=

if tput ce >/dev/null 2>&1
then ## e.g. FreeBSD
    co=co
    li=li
elif tput el 2>/dev/null
then ## e.g. Linux
    co=cols
    li=lines
fi

UNBOLD=$'\E[0m'
standout=$'\E[0;1;7m'
cle=$'\E[K'
clb=$'\E[1K'
ULINE=$'\E[0;4m'
REVERSE=$'\E[0;7m'
BLINK=$'\E[0;5m'
BOLD=$'\E[0;1m'
CINV=$'\E[0;8m'

R=$REVERSE
U=$UNBOLD
B=$BOLD
BR=$B$R
Cl=$'\f'
if [ "$co" ]
then
    tput reset
    COLUMNS=${COLUMNS:=`tput $co`}
else
    COLUMNS=${COLUMNS:-80}
fi
top=6
margin=11
prompt="3 $(( $top + 9 ))"
beep=  #$'\a'
pause=1
KEYMAX=1
KEYECHO=s

while getopts vVhH-:xoX:O:c:p: var
do
 case "$var" in

     x) playerX=human
 playerO-computer
 ;;
     o) playerO=human
 playerX=computer
 ;;
     X) playerX=$OPTARG ;;
     O) playerO=$OPTARG ;;
     c|C) playerO=${OPTARG#*,}
   playerX=${OPTARG%,*}
   ;;
     p) pause=$OPTARG ;;

    -) case $OPTARG in
         help) usage; exit ;;
         verbose) verbose=$(( $verbose + 1 )) ;;
         version) version; exit ;;
       esac
       ;;
    h) usage; exit ;;
    H) longusage=1; usage; exit ;;
    v) verbose=$(( $verbose + 1 )) ;;
    V) version; exit ;;
    *);;
 esac
done
shift $(( $OPTIND - 1 ))

if [ "$co" ]
then
    COLUMNS=`tput $co`
else
    COLUMNS=${COLUMNS:-80}
fi
margin=11  ##$(( ($COLUMNS - 11) / 2 ))
clear

if [ $verbose -ge 1 ]
then
    exec 2>$HOME/tttlog
    set -x
fi

tictactoe
printat $prompt "\n$CVIS\n"
Permisos: chmod 700 tt.bash 
Ejecución: ./ttt.bash
Leer más...

Juego del Ahorcado.

d
Nombre: Ahorcado.bash
Autor: blackman
Descripción: Script que permite jugar "Ahorcado" en la terminal
Visto en Espacio Linux
El script hace uso de un archivo de texto donde va sacando las palabras a adivinar
#!/bin/bash

function message() {
    case $mensage in
 game_banner) #tput cup 1 $cols
   echo
   tput rev
   echo "$(tput setaf 4)EL JUEGO DEL AHORCADO EN BASH SCRIPT$(tput sgr0)"
   echo
   echo "$(tput setaf 7)$(tput bold)Contiene $(tput setaf 1)$(( $long_palabra-$espacios ))$(tput setaf 7) caracteres sin contar los espacios"
   echo "$(tput setaf 7)Puedes usar los comodines. Dispones de $(tput setaf 1)$comodines$(tput setaf 7). Para usarlos pulsa $(tput setaf 1)+"
   [[ $(( 6-intentos )) -lt 2 ]] && vida="vida" || vida="vidas"
   echo "$(tput setaf 7)Dispones de $(tput setaf 1)$(( 6-intentos )) $vida"
   #echo "$(tput setaf 7)El nombre de este país es $(tput setaf 1)$palabra"¡
   echo
   echo "$(tput setaf 7)El nombre de este país es: $(tput setaf 1)$word"
   echo -n "$(tput setaf 7)Vidas: $(tput setaf 1)"
   for (( i=1; i<=$(( 6-intentos )); i++ )); do echo -n $'\342\231\245'; done; echo
   echo -n "$(tput setaf 7)Comodines: $(tput setaf 1)"
   for (( i=1; i<=$comodines; i++ )); do echo -n $'\342\230\245'; done; echo
   echo "$(tput setaf 7)Caracteres restantes: $(tput setaf 1)$(( ($long_palabra-$espacios)-$aciertos ))"
   echo "$(tput setaf 7)Puntuación: $(tput setaf 1)$score";;
 game_over)  echo "$(tput setaf 2)Fenomenal, eres un crack";;
 game_read) read -n1 -p "$(tput setaf 7)Vida $(tput setaf 1)$intentos $(tput setaf 7)de $(tput setaf 1)5$(tput setaf 7). Introduce una letra: $(tput setaf 1)" caracter
   echo;;
 salir)  echo
   tput rev
   echo "$(tput setaf 1)GameOver$(tput sgr0)"
   echo "$(tput setaf 7)$(tput bold)Tu mejor puntuación es: $(tput setaf 1)$best_score"
   echo "$(tput setaf 7)Tu puntuación acumulada es: $(tput setaf 1)$acumulado"
   echo
   echo "$(tput setaf 7)La solución es: $(tput setaf 1)$palabra"
   echo "$(tput setaf 7)Que deseas hacer?"
   read -n1 -p "$(tput setaf 7)Pulsa $(tput setaf 1)Q $(tput setaf 7)para $(tput setaf 1)salir $(tput setaf 7)o $(tput setaf 1)G $(tput setaf 7)para $(tput setaf 1)volver a jugar$(tput setaf 7). Introduce una letra: $(tput setaf 1)" caracter
   echo "$(tput setaf 7)";;
 comodines_restantes) echo "$(tput setaf 4)Te dispones a usar un comodín. Suerte, sólo dispones de $(tput setaf 1)$comodines"
    echo "$(tput setaf 2)Comodín = $(tput setaf 1)$caracter";;
 comodines_finalizados) echo "$(tput setaf 4)Ups, has gastado todos los comodines";;
 continuar) read -n1 -p "$(tput setaf 1)Pulsar cualquier tecla para continuar$(tput setaf 7)";;
 acierto_mal) echo "$(tput setaf 4)Has fallado, ahora tienes un intento menos";;
 #acierto_letra) echo "$(tput setaf 7)Letra introducida: $(tput setaf 1)$letra";;
 acierto_bien) echo "$(tput setaf 2)Muy bien, ya casi lo tienes";;
 acierto_repetido) echo "$(tput setaf 3)Upps, Esa letra ya la has introducido";;
    esac
}
function init {
#file="diccionario"
    file="paises"
    max=$(cat $file | wc -l)
    num=$(( $RANDOM%$max ))
    palabra=$(head -$num $file | tail -1)
    aciertos=0
    #diccionario
    #palabra=$(echo ${palabra%% *,,} | sed 's/á/a/g;s/é/e/g;s/í/i/g;s/ó/o/g;s/ú/u/g')

    palabra=$(echo ${palabra,,} | sed 's/á/a/g;s/é/e/g;s/í/i/g;s/ó/o/g;s/ú/u/g;s/-/ /g;s/Á/a/g')
    long_palabra=${#palabra}
    comodines=$(( long_palabra/4 ))
    score=$(( (comodines*50)+500 ))
    #PROVISIONAL
    ###########################
    #[[ $long_palabra -lt 15 ]] && main;
    ###########################
    unset array[*]
    i=0; espacios=0; unset word
    while [[ $i -le $(( $long_palabra-1 )) ]]
 do
     caracter="${palabra:$i:1}"
     if [[ $caracter = " "  ]]
  then
      (( espacios++ ))
      caracter=" "
  else
      array=( ${array[*]} $caracter )
      caracter="-"
     fi
     word="$word $caracter"
     (( i++ ))
    done
}

function comodin {
    if [[ $comodines -gt 0 ]]
 then
     long_array=$(( ${#array[*]}-1 ))
     index=$(( $RANDOM%${#array[*]} ))
     caracter=${array[$index]}
     i=0
     while [[ $i -le $long_array ]]
  do
      if [[ ${array[$i]} = $caracter ]]
   then
       unset array[$i]
       array2=( ${array2[*]} $caracter )
       (( aciertos++ ))
       score=$(( score+50 ))
      fi
      (( i++ ))
     done
     array=( ${array[*]} )
     array2=( ${array2[*]} )
     (( comodines-- ))
     (( intentos-- ))
     mensage="comodines_restantes"; message mensage
    else
 (( intentos-- ))
 mensage="comodines_finalizados"; message mensage
    fi
    mensage="continuar"; message mensage
    game
}

function acierto {
    unset find
    long_array=$(( ${#array[*]}-1 ))
    i=0
    while [[ $i -le $long_array ]]
 do
     if [[ ${array[$i]} = $caracter ]]
  then
      unset array[$i]
      find="true"
      array2=( ${array2[*]} $caracter )
      (( aciertos++ ))
      score=$(( score+100 ))
     fi
     (( i++ ))
    done
    if [[ $find = "true" ]]
 then
     mensage="acierto_bien"; message mensage
     (( intentos-- ))
 else
     long_array2=$(( ${#array2[*]}-1 ))
     i=0
     while [[ $i -le $long_array2 ]]
  do
      if [[ ${array2[$i]} = $caracter ]]
   then
       find="true"
      fi
      (( i++ ))
     done
     if [[ $find = "true" ]]
  then
      mensage="acierto_repetido"; message mensage
      (( intentos-- ))
      score=$(( score-10 ))
  else
      mensage="acierto_mal"; message mensage
      score=$(( score-50 ))
     fi
    fi
    array=( ${array[*]} )
    array2=( ${array2[*]} )
    mensage="continuar"; message mensage
    game
}
function game {
    clear
    lines=$(( $(tput lines)/10 ))
    cols=$(( $(tput cols)/10 ))
    i=0; unset word;
    while [[ $i -le $(( $long_palabra-1 )) ]]
 do
     letra="${palabra:$i:1}"
     if [[ $letra = " "  ]]
  then
      letra=" "
  else
      unset letra_acertada
      for x in ${array2[*]}
   do
       if [[ $x = $letra ]]
    then
        letra_acertada="true"
       fi
      done
      if [[ $letra_acertada != "true" ]]
   then
       letra="-"
      fi
     fi
     word="$word $letra"
     (( i++ ))
    done
    (( intentos++ ))
    mensage="game_banner"; message mensage
    dibujo
    if [[ $intentos -gt 5 ]]
 then
     [[ $best_score -eq 0 ]] && best_score=0
     [[ $acumulado -eq 0 ]] && acumulado=0
     salir
    fi

    if [[ -z ${array[*]} ]]
 then
     [[ $score -gt $best_score ]] && best_score=$score
     acumulado=$(( acumulado+score ))
     mensage="game_over"; message mensage
     salir
    fi
    mensage="game_read"; message mensage
    if [[ $caracter = "+" ]]
 then
     comodin
    fi
    acierto
}

function dibujo {
    case $intentos in
 1) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo;;
 2) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo "               | "
  echo "               | "
  echo;;
 3) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo "              \| "
  echo "               | "
  echo;;
 4) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo "              \|/"
  echo "               | "
  echo;;
 5) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo "              \|/"
  echo "               | "
  echo "              /  "
  echo;;
 *) echo "________________ "
  echo "               | "
  echo "               | "
  echo "               O "
  echo "              \|/"
  echo "               | "
  echo "              / \\"
  echo;;
    esac
}
function salir {
    mensage="salir"; message mensage
    case $caracter in
 q) clear;exit;;
 g) unset word; unset intentos; unset comodines; unset aciertos; unset score; unset array[*]; unset array2[*];main;;
 *) clear; mensage="game_banner"; message mensage; dibujo; salir;;
    esac
    clear
}

function main {
    init
    game
}
main
Permisos: chmod 700 ahorcado.bash 
Ejecución: ./ahorcado.bash
Y a jugar! :D
Leer más...

CheckHostAlive.bash

d
Nombre: CheckHostAlive.bash
Autor: @Tonejito
Descripción: Script que permite verificar si un host se encuentra arriba en la red,muestra un "0" si está arriba y un "1" si está abajo
Visto en: Tonejito
#!/bin/sh


# Check all hosts within the network
# BSD license


PING=/sbin/ping
SEQ=gseq


NET=192.168.2
ME=192.168.0.2


i=1;
while [ $i -le 254 ] ;
do
  $PING -v -D -s 8 -t 1 -w 1 -c 1 -I $ME $NET.$i 1>/dev/null
  printf "$?"
  i=`expr $i + 1` ;
done


printf "\n"
Permisos: chmod 700 CheckHostAlive.bash 
Ejecución: ./CheckHostAlive.bash.
Nota: El script mandará el ping del primer nódo al último [ 0-254 ]
Leer más...

The shell it's alive!

d
Autor: Ricardo Osorio
Twitter: @HackeaMesta
Descripción: Script que permite que la terminal hable y salude
Visto en: HackeaMesta
#!/bin/bash 

ifespeak=`type -p espeak`
 if [ -z $ifespeak ]; then
  echo "Para mejor funcionamiento necesita tener instalado espeak"
  echo "sudo apt-get install espeak"
  echo "sudo yum install espeak"
  echo "Intentalo nuevamente"
  exit 1
 fi
 
NOMBRE=`cat /etc/passwd | grep "^$LOGNAME" | cut -d: -f5 | cut -d' ' -f1` 
HORA=`date | cut -c12-13 | tr -d ' '` 
tiempo=`date +%H:%M` 
dia=`date +%d` 
mes=`date +%m` 
ano=`date +%Y` 
if expr '$HORA <= 4' > /dev/null  
then 
echo 'Buenas noches, '$NOMBRE | espeak -v es-la -s 150 2>/dev/null 
sleep=1 
echo 'Son las, '$tiempo',, horas,, del '$dia',,,, del '$mes',,,, de '$ano'' | espeak -v es-la -s 140 2>/dev/null 
sleep=1 
echo 'el sistema operativo esta listo para usarse' | espeak -v es-la -s 150 2>/dev/null 
sleep=1 
echo ',,,,que disfrutes tu sesión en Debian' | espeak -v es-la -s 140 2>/dev/null 
elif expr '$HORA < = 11' > /dev/null ] 
then 
echo 'Buenos dias, '$NOMBRE | espeak -v es-la -s 150 
sleep=1 
echo 'Son las, '$tiempo', horas,, del '$dia',,,, del '$mes',,,, de '$ano'' | espeak -v es-la -s 140 
sleep=1 
echo 'el sistema operativo esta listo para usarse' | espeak -v es-la -s 150 
sleep=1 
echo ',,,,que disfrutes tu sesión en Debian' | espeak -v es-la -s 140 
elif  expr '$HORA < = 18' > /dev/null 
then 
echo 'Buenas tardes, '$NOMBRE | espeak -v es-la -s 150 
sleep=1 
echo 'Son las, '$tiempo', horas,, del '$dia',,,, del '$mes',,,, de '$ano'' | espeak -v es-la -s 140 
sleep=1 
echo 'el sistema operativo esta listo para usarse' | espeak -v es-la -s 150 
sleep=1 
echo ',,,,que disfrutes tu sesión en Debian' | espeak -v es-la -s 140 
elif expr '$HORA < = 24' > /dev/null  
then 
echo 'Buenas noches, '$NOMBRE | espeak -v es-la -s 150 
sleep=1 
echo 'Son las, '$tiempo', horas,, del '$dia',,,, del '$mes',,,, de '$ano'' | espeak -v es-la -s 140 
sleep=1 
echo 'el sistema operativo esta listo para usarse' | espeak -v es-la -s 150 
sleep=1 
echo ',,,,que disfrutes tu sesión en Debian' | espeak -v es-la -s 140 
fi
El script detecta 3 zonas horarias 
1. Buenos días
2. Buenas tardes
3. Buenas noches
Dependiendo de que hora sea
Damos permisos de ejecución
chmod +x habla.bash
Ejecutamos el script
./habla.bash
Leer más...

Colores en Bash

d
Autor: JuzsR [ gentoo[at]rocks.net ]
Descripción: Script que mediante el uso de variables permite tener salidas más estéticas en pantalla.
#!/usr/bin/env bash
# Colores en bash
# JuszR gentoo@rocks.net
# GPL
 
# Variables
txtund=$(tput sgr 0 1)          # Subrayado
txtbld=$(tput bold)             # Negrita
bldred=${txtbld}$(tput setaf 1) #  rojo
bldblu=${txtbld}$(tput setaf 4) #  azul
bldwht=${txtbld}$(tput setaf 7) #  blanco
txtrst=$(tput sgr0)             # Resetear
info=${bldwht}*${txtrst}        # Feedback
pass=${bldblu}*${txtrst}
warn=${bldred}!${txtrst}
 
echo "Ejemplos de colores"
echo -e "$(tput bold) norm  negr  subr   tput-colores$(tput sgr0)"
 
for i in $(seq 1 7); do
  echo " $(tput setaf $i)Texto$(tput sgr0) $(tput bold)$(tput setaf $i)Texto$(tput sgr0) $(tput sgr 0 1)$(tput setaf $i)Texto$(tput sgr0)  \$(tput setaf $i)"
done
 
echo -e '$(tput bold)' 'Para Negrita'
echo -e '$(tput sgr 0 1)' 'Para Subrayado'

echo -e "Ejemplo: "
echo -e "$(tput bold) Negrita" "$(tput sgr 0 1)Subrayado"
Para observar la salida del script 
chmod +x colores.bash
./colores.bash
Leer más...

Tweet desde la terminal

d
Autor: Luka Pusic [ pusic93[at]gmail.com ]
Descripción: Twitter status update bot by http://360percents.com
Uso: ./twitterbot.bash [ aqui va el tweet a publicar ]
#!/bin/bash

#Twitter status update bot by http://360percents.com
#Author: Luka Pusic 

#REQUIRED PARAMS
username=" [tu usuario de twitter ]"
password=" [ tu password de twitter ]"
tweet="$*" #must be less than 140 chars

#EXTRA OPTIONS
uagent="Mozilla/5.0" #user agent (fake a browser)
sleeptime=0 #add pause between requests

if [ $(echo "${tweet}" | wc -c) -gt 140 ]; then
 echo "[FAIL] Tweet must not be longer than 140 chars!" && exit 1
fi


if [ "$tweet" == "" ]; then
echo "[ERROR] Nothing to do / missing text."
exit 1;
fi

touch "cookie.txt" #create a temp. cookie file

#INITIAL PAGE
echo "[+] Fetching twitter.com..." && sleep $sleeptime
initpage=`curl -s -b "cookie.txt" -c "cookie.txt" -L --sslv3 -A "$uagent" "https://mobile.twitter.com/session/new"`
token=`echo "$initpage" | grep "authenticity_token" | sed -e 's/.*value="//' | sed -e 's/" \/>.*//'`

#LOGIN
echo "[+] Submitting the login form..." && sleep $sleeptime
loginpage=`curl -s -b "cookie.txt" -c "cookie.txt" -L --sslv3 -A "$uagent" -d "authenticity_token=$token&username=$username&password=$password" "https://mobile.twitter.com/session"`

#HOME PAGE
echo "[+] Getting your twitter home page..." && sleep $sleeptime
homepage=`curl -s -b "cookie.txt" -c "cookie.txt" -L -A "$uagent" "http://mobile.twitter.com/"`

#TWEET
echo "[+] Posting a new tweet..." && sleep $sleeptime
tweettoken=`echo "$homepage" | grep "authenticity_token" | sed -e 's/.*value="//' | sed -e 's/" \/>.*//' | tail -n 1`
update=`curl -s -b "cookie.txt" -c "cookie.txt" -L -A "$uagent" -d "authenticity_token=$tweettoken&tweet[text]=$tweet&tweet[display_coordinates]=false" "http://mobile.twitter.com/"`

#LOGOUT
echo "[+] Logging out..."
logout=`curl -s -b "cookie.txt" -c "cookie.txt" -L -A "$uagent" "http://mobile.twitter.com/session/destroy"`

rm "cookie.txt"
Leer más...