Skip to content

Instantly share code, notes, and snippets.

@bretonics

bretonics/bashTricks.md

Last active Nov 4, 2020
Embed
What would you like to do?
Tricks to remember on the CL
Script source path - ${BASH_SOURCE} contains full bath to script
# /path/to/repo/bin/script
BIN_PATH="$(dirname ${BASH_SOURCE})"  # gets 'bin' directory path script is in
DIR_PATH="$(dirname $BIN_PATH)"       # gets the main 'repo' directory path
Rename file by replacing old text pattern with new (overwrite existing)
for f in *.txt ; do echo "${f/old/new}"; done

for f in *.txt; do mv "$f" `echo $f | sed s/old/new/\`; done
Find symlink to same inode
find -L / -samefile path/to/file.txt
Loop through results of find
find | while read directory; do $directory; done
Find modified n*24 hours ago and remove
n="+15"
find /home/directory/*/dir/* -type d -mtime ${n} -prune -exec rm -rfv "{}" \;
Read in password
read -p "Password: " pswd
echo "User pswd was $pswd"
Array Expansion
${list[@]}

Manipulating Strings

Variable prefix/suffix (extension) removal
${0#*.}
${0%.*}
Variable substring
## syntax ##
${parameter:offset:length}

${a:1}    # everything after position 1
${a:0:5}  # offset 0 with length 5

## syntax ##
${parameter:-default}  # set a default if $parameter udefined

${a:-$b}  # output: ${a} ? ${a} : ${b}
Substring Replacement
# Parameter expansion with substring replacement
# It takes the existing variable username in `=${username` then will replace every occurrence `//` of `*= ` with `/...` (nothing).
# NOTE: the closing '/' is implied
username=${username//*= /}
Substring Removal
# Deletes shortest match of $substring from FRONT of $string.
${string#substring}

# Deletes longest match of $substring from FRONT of $string.
${string##substring}

# Deletes shortest match of $substring from BACK of $string.
${string%substring}

# Deletes longest match of $substring from BACK of $string.
${string%%substring}

# Find and remove (replace with nothing) 'chars followed by any number of zeroes'.
echo "$TEST" | sed 's/chars0*//'
Only print the actual match (not the entire matching line), use a substitution.
# Replace whatever comes before and after the match with nothing, then print the whole line (p)
sed -n 's/.*\([0-9][0-9]*G[0-9][0-9]*\).*/\1/p'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.