BASH

From Alessandro's Wiki
Jump to: navigation, search
  • Bourne Again SHell (Bash) And GNU

common shell commands

tac::                             Reverse lines of files
cat -n::                          Numbering lines
cat -b::                          Numbering non-blank lines
wc -c::                           Counting chars
wc -w::                           Counting words
wc -l::                           Counting lines
head::                            Printing the first lines
tail::                            Printing the last lines
uniq::                            Make duplicate lines unique
uniq -d::                         Print duplicated lines of input
uniq -u::                         Remove all duplicated lines
cat -s::                          Squeezing blank lines
  • Aliases

Un alias serve per associare a un comando una serie di comandi e parametri come segue:

$ alias
alias k1='kill -9 %1'
alias l.='ls -d .* --color=tty'
alias ll='ls -l --color=tty'
alias ls='ls --color=tty'
alias vi='vim'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
alias zombie='ssh -X root@zombie'

grep

  • remove comments:
grep -vE '(^space:*($|(#|!|;|//)))'

head / tail

a=/file_to_get_the_line_range_from
start=30;
stop=50;
let dur=${stop}-${start};
cat $a |head -${stop}|tail -${end}

cat

  • "to cat" a file means the action of opening the file in reading and outputting its contents to terminal.

tr

  • convert new line to spaces
tr '\n' ' '
  • all lines in one
tr '\n' -d

less

  • less +F behaves like doing a "tail -f" but inside less

permissions

  • change only Directory permissions from current directory
find . -type d -exec chmod 775 {} \;
  • change only File permissions from current directory.
find . -type f -exec chmod 664 {} \;
  • add a user to a group (appending)
usermod -a -G agroup auser
  • set sticky bit etc..
chmod 4511 /usr/sbin/fping
ls -l /usr/sbin/fping
-r-s--x--x 1 root root 31360 Mar  8 11:27 /usr/sbin/fping
  • get groups for the user
getent group <groupname>
  • Verification Commands:
   pwck: verify integrity of password files
   grpck: verify integrity of group files
   Example: grpck /etc/group
  • User admin and other commands:
   useradd: Create a new user or update default new user information
   usermod: Modify a user account
   userdel: Delete a user account and related files
   chage: change user password expiry information
   pwconv: convert to and from shadow pass- words and groups.
   pwunconv: convert to and from shadow pass- words and groups.
   grpconv: creates gshadow from group and an optionally existing gshadow
   grpunconv: creates group from group and gshadow and then removes gshadow
   accton: turns process accounting on or off (Red Hat/Fedora/CentOS)
   ac: Prints stats about users connect time (Red Hat/Fedora/CentOS)

recursive sort

  • linux:
find . -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d" "
  • on BSD
find . -type f -exec stat -f "%m %N" {} \; | sort -n | tail -1 | cut -f2- -d" "
  • just find modified files before ONE day from now:
find . -mtime -1

find

  • remove all files in the second nested directory matching the name to an md5 string
find . -regextype posix-extended -mindepth 2 -maxdepth 2 -type d -regex '.*[a-f0-9]{32}'

duplicates

  • user id
getent passwd | cut -d: -f3 | sort -n | uniq -d
  • user name
getent passwd | cut -d: -f1 | sort -n | uniq -d

size

  • list zero byte files
find . -type f -size 0 | xargs ls -ld
  • rename all files and directories in current directory to first character-letter upper case "maiuscole"
for a in *; do echo "$a"; mv "$a" "`echo "$a" | ruby -n -e 'puts $_.capitalize'`" ; done
  • list only directories
ls -d */.

rename

  • rename all files in a directory replacing white space with underscore:
rename ' ' '_' *

Process id

  • current pid in a script
$$

switch

case expression in
   pattern1 )
       statements ;;
   ...
esac

Redirection

  • redirecting standard output and standard error to a file:
commando 2>&1 | tee /tmp/command_output.txt


      # Redirige lo stderr allo stdout.
      # I messaggi d'errore vengono visualizzati a video, ma come stdout.

    i>&j
      #  Redirige il descrittore di file i in j.
      #  Tutti gli output del file puntato da i vengono inviati al file 
      #+ puntato da j.

   >&j
     # Redirige, per default, il descrittore di file 1 (lo stdout) in j. 81       # Tutti gli stdout vengono inviati al file puntato da j.
    0< NOMEFILE
     < NOMEFILE
      # Riceve l'input da un file.
      # È il compagno di ">" e vengono spesso usati insieme.
      #
      # grep parola-da-cercare <nomefile

   [j]<>nomefile
      #  Apre il file "nomefile" in lettura e scrittura, e gli assegna il
      #+ descrittore di file "j".
      #  Se il file "nomefile" non esiste, lo crea.
      #  Se il descrittore di file "j" non viene specificato, si assume per 
      #+ default il df 0, lo stdin.
      #
      #  Una sua applicazione è quella di scrivere in un punto specifico 
      #+ all'interno di un file.
      echo 1234567890 > File    #  Scrive la stringa in "File".
      exec 3<> File             #  Apre "File" e gli assegna il df 3.
      read -n 4 <&3             #  Legge solo 4 caratteri.
      echo -n . >&3             #  Scrive il punto decimale dopo i
                                #+ caratteri letti.
      exec 3>&-                 #  Chiude il df 3.
      cat File                  #  ==> 1234.67890
      # È l'accesso casuale, diamine.
      # Pipe.
      # Strumento generico per concatenare processi e comandi.
      # Simile a ">", ma con effetti più generali.
      # Utile per concatenare comandi, script, file e programmi.
      cat *.txt | sort | uniq > file-finale
      # Ordina gli output di tutti i file .txt e cancella le righe doppie,
      # infine salva il risultato in "file-finale".
  • Insert text at the end of a file (appending):
echo "text at the end of file" >> filewhichweappendto.txt
  • Insert text at the beginning of a file (prepending):
echo "$(echo 'text that will be added as first line' | cat - filewhichweappendto.txt)" > filewhichweappendto.txt

or

echo -e "text that will be added as first line\n$(cat filewhichweappendto.txt)" > filewhichweappendto.txt

or

sed -i '1s/^/text that will be added as first line\n/' filewhichweappendto.txt

error messages

"Insecure directory in $ENV{PATH}"

  • I got this in a command running in a cron, munin-cron.
  • solved adding
PATH=/usr/bin:/bin

into

/etc/cron.d/munin
  • having there the full path for every script, path is not really needed, but required from perl scripts called from munin plugins