- #!/bin/bash
- 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.
- #!/bin/bash
- # A simple copy script
- 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.
Exporting Variable
script1.sh
- #!/bin/bash
- var1=blah
- var2=foo
- echo $0 :: var1 : $var1, var2 : $var2
- export var1
- ./script2.sh
script2.sh
- #!/bin/bash
- echo $0 :: var1 : $var1, var2 : $var2
Note: the name of variable must be same with both sh file.
No comments:
Post a Comment