Created: 2025-01-30 jue 19:09
#!#!/bin/sh
#!/usr/bin/php
#!/usr/bin/python
# Variable local a esta shell
variable=valor
# Variable exportada a los hijos de esta shell
export variable_exportada=valor
# Variable definida solo para un comando
variable_para_un_comando=valor comando
# La entrada sale de un fichero en vez del teclado
sort < fichero
# La entrada sale de un fichero, y la salida va a otro fichero
sort < fichero > fichero_ordenado
# La entrada sale de un fichero, y la salida se agrega al final de un fichero
sort < otro_fichero >> fichero_ordenado
# La salida del primer comando es la entrada del segudo
sort < fichero | less
# La entrada se especifica en el propio script
sort <<FINDEFICHERO
Maria
Pepe
Juan
Susana
Manolo
FINDEFICHERO
# Defino una variable con los ficheros del directorio
variable=$(ls)
$0: El nombre del script$1: Primer parámetro$2: Segundo parámetro$*: Todos los parámetros a partir del primero$#: Número de parámetros del script$*, $1, $2…
importante(){
  echo --------------------------
  echo Aviso: $*
  echo --------------------------
}
importante "Asi se define una funcion en bash"
return en funcionesif o bucles whilecondicion(){
  # AQUÍ SE PODRÍA DECIDIR EL RETORNO CON OTROS COMANDOS
  # O CON IF's ENCADENADOS, PERO COMO EJEMPLO DEVOLVEMOS TRUE
  return 0
}
while condicion
do
  echo Esto es un bucle infinito
done
shift, $*$@0: Todo ha funcionado correctamente0: Ha sucedido algún tipo de error$? inmediatamente después de ejecutar el comandogrep cadena *
exit_code_del_grep=$?
echo grep ha devuelto: $exit_code_del_grep
if utiliza los códigos de error de los programas
0 se considera truefalseif grep cadena *
then
  echo grep ha encontrado algo sin errores
else
  echo grep no lo ha encontrado, o ha habido errores
fi
[[ es un comando externo que ayuda a hacer condiciones con if
TEST(1)                      User Commands                     TEST(1)
NAME
       test - check file types and compare values
SYNOPSIS
       test EXPRESSION
       test
       [ EXPRESSION ]
       [ ]
       [ OPTION
DESCRIPTION
       Exit with the status determined by EXPRESSION.
       --help display this help and exit
       --version
              output version information and exit
       An omitted EXPRESSION defaults to false.  Otherwise, EXPRESSION
       is true or false and sets exit status.  It is one of:
       ( EXPRESSION )
              EXPRESSION is true
       ! EXPRESSION
              EXPRESSION is false
       EXPRESSION1 -a EXPRESSION2
              both EXPRESSION1 and EXPRESSION2 are true
       EXPRESSION1 -o EXPRESSION2
              either EXPRESSION1 or EXPRESSION2 is true
       -n STRING
              the length of STRING is nonzero
       STRING equivalent to -n STRING
       -z STRING
              the length of STRING is zero
       STRING1 = STRING2
              the strings are equal
       STRING1 != STRING2
              the strings are not equal
       INTEGER1 -eq INTEGER2
              INTEGER1 is equal to INTEGER2
       INTEGER1 -ge INTEGER2
              INTEGER1 is greater than or equal to INTEGER2
       INTEGER1 -gt INTEGER2
              INTEGER1 is greater than INTEGER2
       INTEGER1 -le INTEGER2
              INTEGER1 is less than or equal to INTEGER2
       INTEGER1 -lt INTEGER2
              INTEGER1 is less than INTEGER2
       INTEGER1 -ne INTEGER2
              INTEGER1 is not equal to INTEGER2
       FILE1 -ef FILE2
              FILE1 and FILE2 have the same device and inode numbers
       FILE1 -nt FILE2
              FILE1 is newer (modification date) than FILE2
       FILE1 -ot FILE2
              FILE1 is older than FILE2
       -b FILE
              FILE exists and is block special
       -c FILE
              FILE exists and is character special
       -d FILE
              FILE exists and is a directory
       -e FILE
              FILE exists
       -f FILE
              FILE exists and is a regular file
       -g FILE
              FILE exists and is set-group-ID
       -G FILE
              FILE exists and is owned by the effective group ID
       -h FILE
              FILE exists and is a symbolic link (same as -L)
       -k FILE
              FILE exists and has its sticky bit set
       -L FILE
              FILE exists and is a symbolic link (same as -h)
       -O FILE
              FILE exists and is owned by the effective user ID
       -p FILE
              FILE exists and is a named pipe
       -r FILE
              FILE exists and read permission is granted
       -s FILE
              FILE exists and has a size greater than zero
       -S FILE
              FILE exists and is a socket
       -t FD  file descriptor FD is opened on a terminal
       -u FILE
              FILE exists and its set-user-ID bit is set
       -w FILE
              FILE exists and write permission is granted
       -x FILE
              FILE  exists  and  execute  (or  search)  permission  is
              granted
for se pueden hacer bucles sobre una lista de parámetrosseqfor nombre in Maria Juan Pepe Susana Manolo
do
   echo Realizando una vuelta de bucle sobre $nombre
done
# CUIDADO CON LOS NOMBRES DE FICHERO CON ESPACIOS
for fichero in $(ls)
do
   echo El siguiente fichero es $fichero
done
IFS, que suele ser \t \n (tabulador, nueva línea, espacio)IFS#!/bin/bash
ELEMENTOS="
elemento1
elemento 2
elemento 3
elemento4
"
echo "valor actual de IFS (en hexadecimal):" $(printf "%s" "$IFS" | xxd -p)
for ELE in $ELEMENTOS
do
    echo BUCLE: $ELE
done 
IFS=$'\n'
echo "valor actual de IFS (en hexadecimal):" $(printf "%s" "$IFS" | xxd -p)
for ELE in $ELEMENTOS
do
    echo BUCLE: $ELE
done 
Los nombres de fichero pueden contener caracteres de todo tipo (emojis, \n, espacios…)
  touch "antes"$'\n'"después💩"
  echo LS NORMAL
  ls
  echo LS LITERAL
  ls --literal --show-control-chars
  echo LS SIN CONTROLCHARS
  ls --literal --hide-control-chars
La única forma segura es separar los ficheros por $'\0', que no puede aparecer en la mayoría de sistemas de ficheros
  find . -maxdepth 1 -print0 | while read -d $'\0' FILE
  do
      echo FICHERO: $FILE
  done    
$((expresión))# INCREMENTAR LA VARIABLE contador
contador=$(($contador + 1))
Enviar un email
  echo Cuerpo del mensaje | mail -s "Asunto del mensaje" -a ficheroadjunto alvarogonzalezprofesor@gmail.com
Operaciones matemáticas, si no se dispone de bash
  echo 2+2 | bc
whiptail o dialogwhiptail / dialog para hacer un script que muestre información del sistema, con opciones para:
hostname)hostname -I)df | grep)who)#!/bin/bash
dialogo(){
    whiptail --title "Menu" --menu "Elige una opción" 12 50 5 \
             1 "Mostrar el nombre del ordenador"\
             2 "Mostrar las direcciones IP asignadas"\
             3 "Mostrar espacio libre en los discos"\
             4 "Mostrar usuarios con sesión abierta"\
             5 "Salir"
}
resultado_de_dialogo(){
    dialogo 3>&2 2>&1 1>&3
}
casi_pantalla_completa(){
    stty size | awk '{$1-=4;$2-=4}1'
}
casi_ancho_completo(){
    echo $(stty size | cut -d ' ' -f 2) - 4 | bc
}
ejecuta_opcion(){
    case $1 in
        1)
            whiptail --title "Host name" --msgbox "$(hostname)" 9 $(casi_ancho_completo)
            ;;
        2)
            whiptail --title "Direcciones IP" --msgbox "$(hostname -I)" 9 $(casi_ancho_completo)
            ;;
        3)
            whiptail --title "Uso de disco" --msgbox "$(df | grep /dev | grep -v tmpfs)" $(casi_pantalla_completa)
            ;;
        4)
            whiptail --title "Usuarios con sesión" --msgbox "$(who)" $(casi_pantalla_completa)
            ;;
        5)
            echo "Saliendo"
            ;;
    esac
}
respuesta=$(resultado_de_dialogo)
while [ "$respuesta" ] && [ "$respuesta" -ne 5 ]
do
    ejecuta_opcion $respuesta
    respuesta=$(resultado_de_dialogo)
done
bash procesa los siguientes ficheros:
/etc/bash.bashrc (Debian), /etc/bashrc (Centos), ~/.bash_login/etc/profile/ ~/.bashrc
echo ESTOY EN EL FICHERO XXXXXX. Comprueba cuándo se invoca cada fichero.alumno tenga las variables necesarias para utilizar Oracle cada vez que hace login.alumno vea el estado del listener cada vez que inicia una shellBienvenido a ASGBD cada vez que inician una shell.$HOME/estado.sh que muestre el valor de las variables HOME, USER, PATH, ORACLE_HOME, ORACLE_SID, ORACLE_BASE y la hora actual.ORACLE_HOME y ORACLE_SID.source)#!/bin/sh 
ORACLE_HOME=/var/oracle/product/12.1.0/asir_bbdd
ORACLE_SID=asir
PATH=$ORACLE_HOME/bin:$PATH
export ORACLE_HOME
export PATH
export ORACLE_SID
create user..wheel)SQLPlus con autenticación de sistema operativo
SHOW PARAMETER os_authent_prefix; -- Por defecto es 'ops$'
CREATE USER ops$usuario IDENTIFIED EXTERNALLY;
su usuario
sqlplus / 
SQLPlus con autenticación de Oracle
sqlplus sys/alumno as sysdba
tnsnames.orasqlplus sys/alumno@CONEXION as sysdba
tnsnames.oraMYSID=
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = mydnshostname)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = MYSID)
    )
  )
$ORACLE_HOME/network/admin/tnsnames.oratnsnames.ora para conectarse a un servidor remotosqlplus username/password@host:port/sid
sqlplus  puede ejecutarse desde la shellsqlplus -S alumno/alumno <<HEREDOC
set  autocommit off
create table prueba(un_atributo int);
insert into prueba values(1);
insert into prueba values(2);
select * from prueba;
rollback;
HEREDOC
sqlplus -S alumno/alumno <<HEREDOC
set  autocommit off
insert into prueba values(1);
insert into prueba values(2);
spool prueba.txt
select * from prueba;
spool off
rollback;
HEREDOC
less prueba.txt
sqlplus -S sys/alumno as sysdba <<HEREDOC
set colsep ','   
set pagesize 0   
set trimspool on 
set headsep off  
set linesize 1000
set feedback off
set underline off
spool tablas.csv
select table_name, tablespace_name 
  from all_tables
 where owner = 'SYS'
   and tablespace_name is not null;
spool off
HEREDOC
set markup csv onsqlplussqlplus también puede leer scripts de SQL con @
sqlplus -S sys/alumno as sysdba <<HEREDOC
@/camino/al/fichero.sql
HEREDOC
dbstart y /etc/oratabdbstart para arrancar instancias de base de datos/etc/oratabstartup open, así que no se registra en el listener :(# This file is used by ORACLE utilities.  It is created by root.sh
# and updated by either Database Configuration Assistant while creating
# a database or ASM Configuration Assistant while creating ASM instance.
# A colon, ':', is used as the field terminator.  A new line terminates
# the entry.  Lines beginning with a pound sign, '#', are comments.
#
# Entries are of the form:
#   $ORACLE_SID:$ORACLE_HOME:<N|Y>:
#
# The first and second fields are the system identifier and home
# directory of the database respectively.  The third field indicates
# to the dbstart utility that the database should , "Y", or should not,
# "N", be brought up at system boot time.
#
# Multiple entries with the same $ORACLE_SID are not allowed.
#
#
asir:/var/oracle/product/12.1.0/asir_bbdd:Y
/etc/systemd/system. Se controla con la orden systemctl/etc/rc.*. Se está reemplazando por systemd/etc/systemd/system (entre otros)
After)WantedBy)User)[Unit]
Description=Oracle
After=network.target
[Service]
Type=forking
User=alumno
ExecStart=/home/alumno/oracle-al-inicio.sh
ExecStop=/home/alumno/oracle-al-final.sh
[Install]
WantedBy=multi-user.target
Más información con man systemd.service y man systemd.unit
UnitSi el servicio A … | 
A intenta arrancar B | 
Si se apaga B, A también | 
A arranca si B está inicialmente apagado | 
Si falla arranque de B, arranca A | 
|---|---|---|---|---|
BindsTo=B | 
Sí | Sí | Sí | No | 
Requires=B | 
Sí | No* | Sí | No | 
Requisite=B | 
No | No | No | No | 
Wants=B | 
Sí | No | Sí | Sí | 
Fuente: freedesktop
[*] Si B se apaga explícitamente, se apaga A. Si el servicio B termina sin error, no se apaga A
InstallSi el servicio A | 
|
|---|---|
WantedBy=B | 
Equivalente a que B indique Wants=A | 
RequiredBy=B | 
Equivalente a que B indique Required=A | 
systemctl enable SERVICIO
systemctl disable SERVICIO
systemctl start SERVICIO
systemctl stop SERVICIO
systemctl daemon-reloadsystemctl se ejecuta con el parámetro --system por defecto
--user se utilizan los servicios del usuario llamante
$HOME/.config/systemd/user/| Runlevel | Target | Alias | 
|---|---|---|
| 0 | poweroff.target | 
runlevel0.target | 
| 1 | rescue.target | 
runlevel1.target | 
| 3 | multi-user.target | 
runlevel3.target | 
| 5 | graphical.target | 
runlevel5.target | 
| 6 | reboot.target | 
runlevel6.target | 
systemd-analyze plot: Tiempo de carga de cada serviciosystemd-analyze dot: Fichero con todas las dependencias. Puede convertirse en SVG con dot -Tsvg -o nombre-dibujo.svgsystemctl list-dependencies: Servicios necesarios para cargar un servicio. Se pueden listar a la inversa con --reversecron y systemdcron/etc/crontabrun-parts
man run-partssystemd
Más información en man systemd.timer y man systemd.time
[Unit]
Description=Prints date into /tmp/date file
[Service]
Type=oneshot
ExecStart=/usr/bin/sh -c '/usr/bin/date >> /tmp/date'
[Unit]
Description=Run date.service every 10 minutes
[Timer]
OnCalendar=*:0/10
sleep#!/bin/bash
rm $HOME/elbucledebeparar
hay_que_seguir(){
    if [ -e $HOME/elbucledebeparar ]
    then
        return 1
    else
        return 0
    fi
}
SEGUNDOS=3
sleep $SEGUNDOS
while hay_que_seguir
do      
    echo han pasado $SEGUNDOS segundos
    sleep $SEGUNDOS
done
<<-EOF<<'EOF'Process substitutions: Trata una orden como un fichero temporal
  diff <(ls $first_directory) <(ls $second_directory)
mktemp para ficheros temporalesCREATE EXTERNAL JOB$ORACLE_HOMEbegin
   -- BORRAR EL TRABAJO, POR SI YA EXISTE
   dbms_scheduler.drop_job( job_name => 'myjob' );
   -- CREAR TRABAJO Y PONER ARGUMENTOS
   dbms_scheduler.create_job (job_name    => 'myjob',
                              job_type    => 'executable',
                              job_action  => '/bin/touch',
                              number_of_arguments => 1,
                              auto_drop   => true);
   dbms_scheduler.set_job_argument_value ('myjob', 1, '/opt/oracle/product/18c/dbhomeXE/fichero.nuevo');
   -- EJECUTAR TRABAJO
   dbms_scheduler.run_job ('myjob');
end;
/