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 FILE_NAME.sh

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 > PUBLIC_KEY_FILE.pub

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

To check if a package is installed

# For RHEL 
rpm -qa *MY_SEARCH_TERM*
# For Ubuntu
dpkg —list | grep MY_PACKAGE_NAME

Security and user management

Add a user to a Linux user group

To add your user account to a user group

sudo usermod -aG THE_GROUP_NAME $USER 

To add another user to a group

sudo usermod -aG THE_GROUP_NAME THE_USER_NAME 

Leave a comment

Your email address will not be published. Required fields are marked *