Whether you are new or experienced with Bash, here are some useful variables to improve your scripting skills.
Use the $RANDOM variable to generate a random number between 0 and 32767. This can be useful for creating random strings, numbers, or filenames in scripts.
Use the $SECONDS variable to access the number of seconds since a script was started. This can be useful for timing operations or for implementing timeouts in scripts.
Use the $LINENO variable to access the current line number within a script. This can be useful for generating error messages or debugging scripts.
Use the $BASH_VERSION variable to access the version of the Bash shell being used. This can be useful for checking the Bash version and ensuring compatibility with your scripts.
Use the $0 variable to access the name of the script being executed. This can be useful for implementing self-contained scripts that can be invoked by different names.
Use the $# variable to access the number of command line arguments passed to a script. This can be useful for implementing flexible and modular scripts that can handle different numbers of arguments.
7. $@ and $*
Use the $@ and $* variables to access the command line arguments passed to a script as separate values or as a single string, respectively. This can be useful for processing arguments in a variety of ways.
Use the $? variable to access the exit code of the last command executed by a script. This can be useful for checking the success or failure of a command and controlling the flow of a script based on its exit code.
Bonus Bash Knowledge!
In addition to some useful Bash variables, here's some important commands and operators that may ease your scripting workload.
> and >>
You can use the > and >> operators to redirect the output of a command to a file. For example, if you want to save the output of the ls command to a file called "myfiles.txt", you can use the following command: ls > myfiles.txt. The > operator will overwrite the contents of the file, while the >> operator will append the output to the end of the file.
You can use the xargs command to run multiple commands simultaneously. For example, if you have a list of files that you want to delete, you can use the xargs command to delete all of them at once, like this: cat filelist.txt | xargs rm.
You can use the fc command to edit the last command that you ran. For example, if you want to edit the last command you ran, you can use the following command: fc. This will open the last command in your default text editor, where you can make changes and save the file. When you exit the editor, the edited command will be executed.
You can use the time command to measure the time it takes for a command to run. For example, if you want to measure the time it takes for the ls command to run, you can use the following command: time ls. This will display the time it took for the command to run, as well as other information such as the user and system time used.