Useful Bash commands

Most of these commands work in all Linux, MacOSX, and Unix shells, but some of them only work in selected shells.

Find files recursively by file name pattern

find . -name '*.MY_EXTENSION'

Find files, but exclude a directory from the search. (The -print is needed at the end of the line)

find . -path ./tmp/windows -prune -o -name '*.MY_EXTENSION' -print

Get the absolute path of files recursively

find `pwd` -name MY_FILENAME

Delete files recursively by file name pattern

Works in zsh but not in sh or bash.
New versions of bash cannot do this by default only if the shell option globstar is enabled:
shopt -s globstar
The globbing pattern is **/*.o but that is not limited to files.

find . -type f -name '*.MY_EXTENSION' -delete

Make a shell script file executable

chmod u+x

Directory Listing

Sort by date, most recent on top

ls -lt

Sort by date oldest on top

ls -ltr

Sort by date, display only last modification date and file name

ls -lt | awk '{print $7,$8,$9, $10}'

Display the CHMOD numbers in the output of the ls command

ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/) \
 *2^(8-i));if(k)printf("%0o ",k);print}'

Generate a public SSH key from the private key

ssh-keygen -y -f PRIVATE_KEY_FILE.pem >

Replace all spaces in every filename and directory name recursively with dash

find . -name “* *” -print0 | sort -rz | \
while read -d $’\0′ f; do mv -v “$f” “$(dirname “$f”)/$(basename “${f// /-}”)”; done

Leave a comment

Leave a Reply