Friday, November 29, 2019

[Unix / Linux Shell Tutorial - Lession5] Variables

Example 1: test.sh
  1. #!/bin/bash
  2. echo $1 $2

Now run it: ./test.sh => Nothing print in Terminal
./test.sh Hello => Hello string was show
./test.sh Hello World => Hello World was show

For instance we could run the command ls -l /etc-l and /etc are both command line arguments to the command ls. We can do similar with our bash scripts. To do this we use the variables $1 to represent the first command line argument, $2 to represent the second command line argument and so on. These are automatically set by the system when we run our script so all we need to do is refer to them.

  1. #!/bin/bash
  2. # A simple copy script
  3. cp $1 $2

Line 4 - run the command cp with the first command line argument as the source and the second command line argument as the destination.

There are a few other variables that the system sets for you to use as well.
  • $0 - The name of the Bash script.
  • $1 - $9 - The first 9 arguments to the Bash script. (As mentioned above.)
  • $# - How many arguments were passed to the Bash script.
  • $@ - All the arguments supplied to the Bash script.
  • $? - The exit status of the most recently run process.
  • $$ - The process ID of the current script.
  • $USER - The username of the user running the script.
  • $HOSTNAME - The hostname of the machine the script is running on.
  • $SECONDS - The number of seconds since the script was started.
  • $RANDOM - Returns a different random number each time is it referred to.
  • $LINENO - Returns the current line number in the Bash script.
If you type the command env on the command line you will see a listing of other variables which you may also refer to.


Exporting Variable

script1.sh
  1. #!/bin/bash
  2. var1=blah
  3. var2=foo
  4. echo $0 :: var1 : $var1, var2 : $var2
  5. export var1
  6. ./script2.sh


script2.sh
  1. #!/bin/bash
  2. echo $0 :: var1 : $var1, var2 : $var2


Note: the name of variable must be same with both sh file.


No comments:

Post a Comment

Back to Top