Tuesday 25 February 2014

BASH command line intercept and procession


Bash command is is the interface for sysadmin to control the bash. It is very important for sysadmin to understand how BASH intercepts the command. Here is the brief introduction how it is working.

  • split the command into tokens using delimiters.The delimiters include SPACE, TAB, NEWLINE, ; , (, ), <,  >, |, &
  • build the command stack (complicated process, not discussed here)
  • check if the first token of command is an alias, if it is, it will replace the alias with the value.
  • expand the {}, eg. It will expand a{a,b} to aa and ab
  • if the token is started with ~, it will replace with the home directory
  • any expression started with $, it will replace it with expression value.
  • execute the command in between ``
  • calculate the $((expression)) and replace it with result
  • wildcast expansion. Such as * ? , [ / ]
  • find the exact commands (buildin, $PATH)
  • IO redirection


Here is an example.

echo ~/i* $PWD `echo Yahoo Hadop` $((21*20)) > output

step 1. split the command into tokens
token[1] = echo
token[2] = ~/i*
token[3] = $PWD
token[4] = `echo Yahoo Hadop`
token[5] = $((21*20))
> output are not the tokens, they will be process in the IO rediretion.
Step 2,3,4 skipped
Step 5. replace ~ with /root. So the command is looking like
echo /root/i* $PWD `echo Yahoo Hadop` $((21*20))
step 6. replace $PWD with the current path for example it is:
              echo /root/i* /root `echo Yahoo Hadop` $((21*20))
step 7. excute the command in ``. so it would look like (iteriter process)
        echo /root/i* /root Yahoo Hadop $((21*20))
step 8. calculate the value in $(()). so it would look like
        echo /root/i* /root Yahoo Hadop 420
step 9: expand the wildcast.(take example)
        echo /root/indirect.sh /root/install.log /root/install.log.syslog /root Yahoo Hadop 420

now the BASH is ready to execute the commands as echo is a buidin command
        it will redirect the output to ouput file

No comments:

Post a Comment