Posts

Showing posts with the label bash

Get filename without path, filename without extension, extension of filename in Bash

SOURCE Get filename without path basefilename=$(basename /full/path/to/file.txt) Get filename without extension filewoext="${basefilename%.*}" Get extension of file fileext="${basefilename##*.}"

Arrays in Bash

#!/usr/bin/env bash # Create the array myarray = () # Add items to the array # Add a sequence of numbers from 1 to 16 #for item in {0..16} cd ~/Documents/ # Add a list of files to the array # List all *.txt files in the ~/Documents directory and grab the three oldest # To grab the 3 most recent files use ls -rt. Order by time in reverse with most recent listed last for item in $( ls -t *.txt  | tail -3 ) do   myarray+ = (" ${item} ") done # Iterate over the array and print out items for item in ${myarray[ @ ]} do   printf " Item: ${item}\n " done # Print out the number of elements in the array printf " ${#myarray[ @ ]}\n "

Backup script for Linux or OS X

A simple backup script for backing up my laptop. I have an OS X and Linux laptop so I wanted one script to put on both of them: #!/usr/bin/env homedir="$(echo $HOME)" dom=$(date +%d) ################### # START CONFIGURATION ################### # On the 15th of the month run an rsync --delete to clean out old file. Otherwise just run a regular rsync. if [ ${dom} -eq 15 ]; then   rsynccmnd="rsync --delete -avhz --stats --progress" else   rsynccmnd="rsync -avhz --stats --progress"fi # Path to the exclude file host=$(uname -a|cut -d ' ' -f 1) if [ "${host}" = "Darwin" ]; then  # OS X  excludefile="path to exclude file for OS X"  #EXAMPLE  # excludefile="${homedir}/Documents/Backup/backuplaptop_exclude_osx.txt" else  # Linux  #excludefile="path to exclude file for Linux"  #EXAMPLE  # excludefile="${homedir}/Documents/Backup/backuplaptop_exclude_linux.txt" fi # ...

Argument list too long

I've run into this running rm * and du -hcs *. Solution is to pass the command via pipe and use xargs: find . -name 'filename*' | xargs rm

Bash substrings

Say you have lines in a file that are of the format: 123:200105 and you need to split out the strings to work with them. string=123:201004 string2=${string:0:3} # result is 123 string3=${string:4:6} # result is 201004

Multiline comments in bash

:<<MULTILINECOMMENT echo "foo" echo "bar" this="variable" MULTILINECOMMENT