Linux Classroom Series – 28/Aug/2020

Variable Scopes in Shell scripts

  • Lets create two shell scripts
    name="Learning Thoughts"
    echo "This is from script 1 name= ${name}"
    echo "This is script2"
    echo "Value of name is ${name}"
  • From script1 lets call script2 and try to see if the variable defined in script1 is available for use in script2
  • lets execute Preview
  • The value of name is not available in script2. The default scope of variable is the same script file.
  • So lets find out if there is any other way to pass the variable from script1 to external scripts,
    1. add Arguments to script2
    # replace this with
    ./ $name
    1. export the variable using export statement in script1. so lets change
    name="Learning Thoughts"
    echo "This is from script 1 name= ${name}"
    export name

Debugging your scripts

  • As the script grows and decision paths are included with conditional statements, we start using looping structures etc, we may need some level of debugging to analyse the scripts.
  • This can be done as bas provides two options for us
    • -v option
    • -x option
  • Create a bash script with the following content

echo "the zeroth argument is $(basename $0)"
echo "Hello $*"
  • Now execute this script with the following command
bash -v ./ khaja ibrahim


  • -v option displays the verbose output from bash
  • -x option, which displays the commands as they are executed and is most commonly used.
  • Now lets run the script
bash -x ./ khaja ibrahim


  • This way shows how the evaluated and is very helpful to know the decision branch that has been chosen by the script.
  • Install bash debug plugin in visual studio code and we can debug the shell script. Preview Preview
  • Now we can debug the shell script Preview Preview
  • This approach works with visual studio code installed on the linux desktops or mac.

Enhancing interactive scripts

  • Lets understand how to limit number of characters entered Preview
  • so limit number of characters to be entered, lets run the same command with one more option Preview
  • Lets understand how to control visibility of entered text, If we request for sensitive content like pin/password etc, its not a good approach to show the text while user is typing, Shell gives an option of hiding text when the user is typing. This can be achieved by adding a -s option to read command Preview

Next Steps:

  • How to make my shell scripts understand options (named parameters)
./ --url <>  --location-to-save /home/ubuntu/test.txt

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin