Variables are the names you give to computer memory locations which are used to store values ( can think of them as a container) that can vary over time.
Passing argument to a bash shell script:
Lets create a script lines_count_script.sh that will print total number of lines present in whatever the file user provides,
I have already created one more file lines_count.txt which has five lines of text.
Now run the script lines_count_script.sh and see the output.
Type ./ and script file name as shown below and press enter.
It will prompt you to enter the file name.
Enter file name to print the number of lines.
Hit Enter key and will show the number of lines as output.
Instead of prompting the user for file name we can make the user to pass the file name as command line argument by doing the following change in the script lines_count_script.sh ,
Now simply pass the file name as command line argument while running the script as follows,
The first bash argument (also known as a positional parameter) can be accessed within your bash script using the $1
variable.
Passing multiple arguments to a bash shell script:
Lets create a new script multiple_files_lines_count.sh which will accept multiple arguments as command line parameters and gives the output.
Now run the script and pass three files as arguments to the bash script,
Special variables in Bash shell:
Bash has a lot of built-in special variables that are quite useful.
Lets check the special variables in action,
Run the script and the output looks like below,