Friday, April 29, 2016

How to call a shell script from another shell script

Note: Make sure to add #!/bin/bash to the first line of the script and make it executable through chmod 700 <path to script>.
  1. <path to script> or /bin/bash <path to script> or <scriptname> (add script to $PATH environment variable and call as normal command)
    - child script is executed in a new shell, changes in child script does not affect parent script
    - can be executed asynchronously through background command
  2. <path to script> &
    - same as no. 1 but executes child script on background
  3. source <path to script> or . <path to script>
    - child script is executed in a current shell
    - context is same as parent script (vars and functions of child script becomes visible on parent script)
    - exit call in child script will also exit the parent script
  4. exec <path to script>
    - terminates the current shell and executes on a new shell

Wednesday, April 27, 2016

How to create Bash Script on Mac

  1. Create the bash script file.
    Sample: File myscript.sh
    #!/bin/bash     #”hash-bang" or “she-bang" indicating that this script is to be interpreted and run by the bash shell
    echo hello world     #prints “hello world”
    
  2. Change the file permission to make it an executable. Open the terminal, navigate to the location of the file and type the following command:
    chmod 700 myscript.sh 
    See this link for more info on chmod: http://www.thinkplexx.com/learn/article/unix/command/chmod-permissions-flags-explained-600-0600-700-777-100-etc
  3. Run the script. Type the following in the terminal:
    ./myscript.sh