Tuesday, April 22, 2014

Bash Specialities, part 2

This post shows different examples of usage for file descriptors in bash and few interesting linux commands and features.

Linux Commands:
  • if you like to repeat last command, e.g. when you need to execute it with sudo just type sudo !! 
  • to attach process to an terminal use reptyr PID 
  • to start instant editor type CTRL+x+e 
  • to number lines in file you can use tool nl 
  • ss will display socket statistics
  • if you made a typo in previous command, or you want to run it again with small change use ^lls^ls (in this case if last command was lls -a, this will modify the lls to ls and run valid command ls -a)
  • to show current tty just type tty 
  • to show size of each folder in directory use du -h --max-depth=1   
  • to reuse all parameters of the previous command: !*

Add numbers from command output:
echo -e "4\n6" | gawk '{i+=$1} END {print i}'
echo -e "4\n6" | paste -sd+ - | bc

Working with file descriptors (FD):
Open and close FD:
# open FD for write
exec 97>$file
echo Good redirect >&97
# close FD
exec 97>&-
echo Bad redirect >&97

Different usages of FD with while and read:
# open FD for read
echo -e "\nREAD from FD"
exec 96<$file
while read -ru96 a b; do
    echo A: $a B: $b
done

# open FD for read
echo -e "\nREAD from FD 2"
while read -ru95 a b; do
    echo A: $a B: $b
done 95<$file

# open FD for read
echo -e "\nREAD from FD 3"
while read -r a b; do
    echo A: $a B: $b
done <$file

Another FD operations:
# open file for read and write
exec 94<>$file
# read 7 possitions (the FD will be set on 8th after)
read -n 7 <&94
# insert from actual FD possition, text will be overwritten
echo -n ":INSERT INTO TEXT:" >&94
# close output FD
exec 94>&-

No comments:

Post a Comment