# Bash The Bourne Again SHell is common on GNU/Linux systems and it is worth knowing a bit about it as it can be leveraged to great advantage with just a little knowledge. # General Syntax ==== For loops ==== ```bash # List the file names for i in $( ls ); do echo item: $i done # Loop over range of numbers for i in `seq 0 9`; do echo $1 done ``` ## Default Variables Bash has many default variables, here are some | Variable | Description | | `"${BASH_SOURCE[0]}"` | The directory from which a script is being called | ## Parsing Arguments ## Arrays You must `declare` a variable to be an array, after doing so you can assign items to an array and subsequently access elements by index or loop over them... ```bash declare -a AN_ARRAY AN_ARRAY=( element1 element2 element3 element4 element5 ) # Indexing starts at zero AN_ARRAY[0] # Loop over elements for ELEMENT in "${AN_ARRAY[@]}"; do echo $ELEMENT done ``` # Archiving Create an archive with the current date (or time if you choose to format it as such) using... ```bash tar cjvf archive-$(date +"%Y-%m-%d").tar.bz2 * ``` # Script Tricks ## Insert date You can insert a date in-line by using the following with the desired format... ```bash $(date +"%Y-%m-%d") $(date +"%F") # equivalent to above $(date +"$s") # seconds since epoch $(date +"%Y-%m-%d-%H:%M:%S") $(date +"%F-%X") # equivalent to above ``` ## Make a directory for every file Make a directory for every file You can use [variable substitution](http://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion) to quickly make a directory for every file in a given location (from [here](https://unix.stackexchange.com/a/220026/39149)). ```bash cd path/to/directory FILE_EXT="txt" for x in *.txt; do mkdir "${x%\.txt}" && mv "$x" "${x%\.}" done ``` ## Batch rename files This is easy if you actually use ZSH rather than Bash courtesy of [zmv](https://blog.smittytone.net/2021/04/03/how-to-use-zmv-z-shell-super-smart-file-renamer/). ## Multi-character arguments See [here](https://unix.stackexchange.com/a/353639/39149) ## xarg * [Command-Line Finding and Filtering — Sympolymathesy, by Chris Krycho](https://v5.chriskrycho.com/journal/follow-up-on-command-line-finding-and-filtering/) ## Options [Small getopts tutorial Bash Hackers Wiki](https://wiki.bash-hackers.org/howto/getopts_tutorial) ## My scripts * [[bash:scripts:aws_exports|aws_exports.sh]] * [[bash:scripts:aws_exports_parallel|aws_exports_parallel.sh]] # Links * [Bash-hackers.org](http://wiki.bash-hackers.org/)