Passing Command-Line Arguments to Bash Scripts
I’m sure this one will be obvious to many readers, but it wasn’t to me, so I’m going to share it. A bash script is a file that you can run at the command line in Linux/Unix environments to automate something. In my case, I have a Java program that I need to run over and over again, so I created a bash script to make this easier rather than having to type the same long command repeatedly. These scripts are quite flexible and allow you do even programming constructs like functions, for loops, and if statements, etc.
Let’s say you have a simple bash script. The file name is test. And the contents of the file are the following:
#!/bin/bash echo 'Hello World!'
You would invoke this at the command line (from the directory where it resides) by entering:
./test
Now let’s say you want to be able to pass an argument to it. You could modify the script to this.
#!/bin/bash echo 'Hello World!' echo 'The argument is:' echo $1
You would invoke this at the command line by entering:
./test whatup
This would print out:
Hello World!
The argument is:
whatupAs far as I know, the command-line arguments can only be referenced by their index (in this case, it was the number 1 because it was the first argument). But you could get more creative if you wanted to.
This article has more detail on how to create bash scripts:
